How to use dictionaries in Python

Dictionaries are a powerful data structure in Python. They are similar to lists, but instead of using integer indices to access items, they use keys, which can be any immutable type such as strings, numbers, or tuples.

To create a dictionary, you use curly braces {} and assign key-value pairs. For example:

my_dict = {
“name”: “John Doe”,
“age”: 42

You can access values in the dictionary by using their keys. For example:

name = my_dict[“name”]

To add a new key-value pair to the dictionary, you can use the syntax:

my_dict[“job”] = “programmer”

To delete an item from the dictionary, you can use the del keyword:

del my_dict[“age”]

You can also loop through the dictionary using a for loop:

for key, value in my_dict.items():
print(key, value)

Finally, you can use the len() function to get the number of key-value pairs in the dictionary:

num_items = len(my_dict)