Dictionary Operations

One of the most important data structures in Python is the dictionary. A dictionary is an unordered collection of key-value pairs, where each key is unique. In this article, we’ll cover some of the most common operations you can perform with dictionaries in Python.

Creating a Dictionary

A dictionary in Python can be created using curly braces {} or the dict() constructor. The key-value pairs are separated by a colon : and each pair is separated by a comma ,. For example, the following code creates a dictionary with three key-value pairs:

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

You can also create a dictionary using the dict() constructor and passing in a list of tuples, where each tuple represents a key-value pair:

my_dict = dict([('name', 'John Doe'), ('age', 30), ('city', 'New York')])

Accessing Dictionary Elements

You can access the elements of a dictionary using square brackets [] and the key. For example, to access the value of the 'name' key in the above dictionary, you would do the following:

print(my_dict['name'])
# Output: John Doe

If you try to access a key that doesn’t exist in the dictionary, a KeyError will be raised. To avoid this, you can use the get() method, which returns None if the key is not found, or a default value if you provide one as a second argument:

print(my_dict.get('email'))
# Output: None

print(my_dict.get('email', 'Not found'))
# Output: Not found

Modifying Dictionary Elements

You can add a new key-value pair to a dictionary using square brackets [] and assigning a value to the key:

my_dict['email'] = 'johndoe@example.com'
print(my_dict)
# Output: {'name': 'John Doe', 'age': 30, 'city': 'New York', 'email': 'johndoe@example.com'}

You can also modify an existing value by reassigning a new value to the key:

my_dict['age'] = 31
print(my_dict)
# Output: {'name': 'John Doe', 'age': 31, 'city': 'New York', 'email': 'johndoe@example.com'}

Removing Dictionary Elements

You can remove a key-value pair from a dictionary using the del statement:

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

You can also remove all key-value pairs from a dictionary using the clear() method:

my_dict.clear()
print(my_dict)
# Output: