Dictionary in Python with Examples

In Python, a dictionary is an unordered collection of key-value pairs, where each key must be unique. Dictionaries are often used to store and retrieve data quickly, as opposed to iterating through a list or tuple. Here’s an example of a basic dictionary in Python:

# create a dictionary
my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}

# access a value using its key
print(my_dict["key1"])

# update a value in the dictionary
my_dict["key2"] = "new_value2"

# add a new key-value pair to the dictionary
my_dict["key4"] = "value4"

# delete a key-value pair from the dictionary
del my_dict["key3"]

# iterate through the keys in the dictionary
for key in my_dict:
    print(key)

# iterate through the key-value pairs in the dictionary
for key, value in my_dict.items():
    print(key, value)

In the example above, the my_dict dictionary contains three key-value pairs when it is created. We can access a value in the dictionary by using its key, just like we would with an index in a list. We can also update a value in the dictionary by assigning a new value to the key. We can add a new key-value pair to the dictionary by assigning a value to a new key, and we can delete a key-value pair using the del keyword.

We can also iterate through the keys in the dictionary using a for loop, or we can iterate through the key-value pairs using the items() method. In the second loop, the key and value variables are used to store the current key-value pair being accessed in the dictionary.

Leave a Comment