Python - Dictionary

A dictionary in Python is a collection of key-value pairs. It is an unordered collection, which means that the order of elements in a dictionary is not guaranteed. The keys in a dictionary must be unique, immutable, and hashable. Values can be of any data type and can be duplicated. Dictionaries are denoted by curly braces {} and each key-value pair is separated by a colon :.

Here is an example of a dictionary in Python:

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

In this example, the keys are 'name', 'age', and 'city', and the corresponding values are 'John', 30, and 'New York'. We can access the values of a dictionary by using the keys as follows:

print(my_dict['name'])  # Output: John
print(my_dict['age'])   # Output: 30
print(my_dict['city'])  # Output: New York

We can also add or modify key-value pairs in a dictionary as follows:

my_dict['occupation'] = 'Software Engineer'
print(my_dict)  # Output: {'name': 'John', 'age': 30, 'city': 'New York', 'occupation': 'Software Engineer'}

my_dict['age'] = 35
print(my_dict)  # Output: {'name': 'John', 'age': 35, 'city': 'New York', 'occupation': 'Software Engineer'}

Finally, we can remove key-value pairs from a dictionary using the del keyword:

del my_dict['occupation']
print(my_dict)  # Output: {'name': 'John', 'age': 35, 'city': 'New York'}