Dictionaries in Python: Everything You Need to Know

Per aspera ad astra
4 min readJan 27, 2023

--

Dictionaries, also known as associative arrays or hash maps, are a fundamental data structure in Python. They are used to store key-value pairs, where each key is unique and is used to access its associated value. In this lesson, we will cover the basics of dictionaries, including how to create, access, and manipulate them.

Creating a Dictionary

To create a dictionary in Python, we use curly braces {} and separate keys and values with a colon. For example:

# Creating a dictionary
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
print(my_dict)

Output:

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

Alternatively, you can also create a dictionary using the dict() constructor:

# Creating a dictionary using the dict() constructor
my_dict = dict(name='John', age=30, city='New York')
print(my_dict)

Output:

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

Accessing Dictionary Elements

To access elements in a dictionary, we use the square brackets [] and the key. For example:

# Accessing elements in a dictionary
print(my_dict['name']) # Output: John

You can also use the get() method to access elements in a dictionary. This method returns the value of the key if it exists in the dictionary, and None if it does not. For example:

# Using the get() method
print(my_dict.get('age')) # Output: 30

Manipulating Dictionaries

You can add, update, and delete elements in a dictionary using the following methods:

  • Adding an element: To add an element to a dictionary, you can use the square brackets [] and assign a value to a new key. For example:
# Adding an element to a dictionary
my_dict['gender'] = 'male'
print(my_dict)

Output:

{'name': 'John', 'age': 30, 'city': 'New York', 'gender': 'male'}
  • Updating an element: To update an existing element in a dictionary, you can use the square brackets [] and assign a new value to an existing key. For example:
# Updating an element in a dictionary
my_dict['age'] = 35
print(my_dict)

Output:

{'name': 'John', 'age': 35, 'city': 'New York', 'gender': 'male'}
  • Deleting an element: To delete an element from a dictionary, you can use the del keyword and the key. For example:
# Deleting an element from a dictionary
del my_dict['gender']
print(my_dict)

Output:

{'name': 'John', 'age': 35, 'city': 'New York'}

Dictionary Methods

Python provides several built-in methods to work with dictionaries, such as:

  • keys(): This method returns a view object that displays a list of all the keys in the dictionary. For example:
Copy code
# Using the keys() method
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
print(my_dict.keys()) # Output: dict_keys(['name', 'age', 'city'])
  • values(): This method returns a view object that displays a list of all the values in the dictionary. For example:
# Using the values() method
print(my_dict.values()) # Output: dict_values(['John', 30, 'New York'])
  • items(): This method returns a view object that displays a list of all the key-value pairs in the dictionary. For example:
# Using the items() method
print(my_dict.items()) # Output: dict_items([('name', 'John'), ('age', 30), ('city', 'New York')])
  • clear(): This method removes all items from the dictionary. For example:
# Using the clear() method
my_dict.clear()
print(my_dict) # Output: {}
  • copy(): This method returns a shallow copy of the dictionary. For example:
# Using the copy() method
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
my_dict_copy = my_dict.copy()
print(my_dict_copy) # Output: {'name': 'John', 'age': 30, 'city': 'New York'}
  • pop(): This method removes and returns an item from the dictionary with a specified key. If the key is not found, it returns a specified default value. For example:
# Using the pop() method
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
print(my_dict.pop('age')) # Output: 30
print(my_dict) # Output: {'name': 'John', 'city': 'New York'}
  • popitem(): This method removes and returns an arbitrary key-value pair from the dictionary. For example:
# Using the popitem() method
print(my_dict.popitem()) # Output: ('name', 'John')
print(my_dict) # Output: {'city': 'New York'}
  • update(): This method updates the dictionary with key/value pairs from another dictionary, or from an iterable of key/value pairs. For example:
# Using the update() method
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
my_dict_2 = {'gender': 'male', 'age': 35}
my_dict.update(my_dict_2)
print(my_dict) # Output: {'name': 'John', 'age': 35, 'city': 'New York', 'gender': 'male'}

These are just a few examples of the methods available for working with dictionaries in Python. It’s important to note that the keys in a dictionary must be unique and immutable (i.e., they cannot be changed), while the values can be of any data type and can be repeated.

Another important aspect of dictionaries is the concept of nested dictionaries. A nested dictionary is a dictionary that contains another dictionary as its value. For example:

# Creating a nested dictionary
my_dict = {'name': 'John', 'age': 30, 'address': {'street': 'Main', 'city': 'New York'}}

In this example, the value of the ‘address’ key is a dictionary itself, containing information about the street and city. To access the values of the nested dictionary, we can use the keys of the nested dictionary as indexes. For example:

# Accessing values of a nested dictionary
print(my_dict['address']['city']) # Output: 'New York'

It’s also possible to add, modify, and delete elements in a nested dictionary using the same methods and operations as for a regular dictionary.

In conclusion, dictionaries are an essential data structure in Python, providing a flexible and efficient way to store and retrieve data. The built-in methods and operations make it easy to work with dictionaries and perform common tasks such as adding, modifying, and removing elements. Understanding and mastering the use of dictionaries will greatly enhance your ability to write efficient and effective Python code.

--

--