Dictionaries in Python (25/100 Days of Python)

Martin Mirakyan
5 min readJan 26, 2023

--

Day 25 of the “100 Days of Python” blog post series covering dictionaries

Python dictionaries are a powerful and versatile data structure that can be used to store and organize data in a way that is easy to access and modify. They are similar to lists but, instead of using numerical indexes to access items, dictionaries use keys. In this tutorial, we will learn how to create, access, and modify dictionaries in Python and explore real-world examples of how to use them in web development and data analysis.

Creating a Python Dictionary

To create a dictionary in Python, we use curly braces {} and separate keys and values with colons:

# Create a dictionary with predefined values
grades = {'John': 'A', 'Anna': 'B', 'Bob': 'C'}

# Create an empty dictionary and add values one by one
grades = {}
grades['John'] = 'A'
grades['Anna'] = 'B'
grades['Bob'] = 'C'

In this example, the keys are John, Mary, and Bob, while the values are A, B, and C respectively. This dictionary represents the grades of three students. Both of the approaches above will result in the same final dictionary: {'John': 'A', 'Anna': 'B', 'Bob': 'C'}. You can verify this by printing the variablegrades in the end.

Accessing Items in a Python Dictionary

Similar to lists, to access an item in a dictionary, we use the key in square brackets []:

print(grades['John'])   # 'A'
print(grades['Bob']) # 'C'
print(grades['David']) # KeyError

If we try to access a key that does not exist in the dictionary, it will raise a KeyError. To avoid this, we can use the get() method, which returns None if the key does not exist, or the default value if we provide as a second argument:

print(grades.get('Tom'))          # None
print(grades.get('David', 'F')) # 'F'
print(grades.get('Bob', 'F')) # 'C'

Modifying Items in a Python Dictionary

To modify an item in a dictionary, we use the key in square brackets [] and assign a new value:

grades = {'John': 'A', 'Anna': 'B', 'Bob': 'C'}

# Imagine there was a mistake in the reference answers of a test
# We need to update the grades for some students
grades['John'] = 'B' # Oops the grade was lowered
grades['Anna'] = 'A' # Anna's answer was actually correct
print(grades) # {'John': 'B', 'Anna': 'A', 'Bob': 'C'}

Keep in mind that we can also add a new item to the dictionary by using a new key in square brackets and assigning a value as displayed in the very first example:

grades = {'John': 'A', 'Anna': 'B', 'Bob': 'C'}
grades['David'] = 'A'
grades['John'] = 'B'
grades['Simon'] = 'C'
print(grades)
# {'John': 'B', 'Anna': 'B', 'Bob': 'C', 'David': 'A', 'Simon': 'C'}

Removing Items from a Python Dictionary

To remove an item from a dictionary, we can use the del keyword and the key in square brackets:

grades = {'John': 'B', 'Anna': 'B', 'Bob': 'C', 'David': 'A', 'Simon': 'C'}
del grades['David'] # David was actually taking another class
print(grades) # {'John': 'B', 'Anna': 'B', 'Bob': 'C', 'Simon': 'C'}
del grades['David'] # KeyError - you are not allowed to items not in the dict

Note that you can’t remove the item twice or remove an item that’s not in the dictionary. That will result in a KeyError.

We can also use the pop() method and the key. This method returns the value of the removed item, which can be useful for printing or performing some operation on a removed item:

grades = {'John': 'B', 'Anna': 'B', 'Bob': 'C', 'David': 'A', 'Simon': 'C'}
grade = grades.pop('David')
print('David had a grade of', grade) # David had a grade of A
print(grades) # {'John': 'B', 'Anna': 'B', 'Bob': 'C', 'Simon': 'C'}
grades.pop('David') # KeyError

Iterating over a Python Dictionary

There are 3 methods that are very useful when iterating over dictionaries:

  1. keys() — Returns all the keys in the dictionary (names in our example)
  2. values() — Returns all the values in the dictionary (grades in our case)
  3. items() — Returns a list of (key, value) tuples (name & grade together)

To iterate over a dictionary, we can use a for loop and the keys() method to access the keys of the dictionary, and then use the keys to access the values:

grades = {'John': 'B', 'Anna': 'B', 'Bob': 'C', 'David': 'A', 'Simon': 'C'}
for name in grades.keys():
print(name, '-->', grades[name])
# John --> B
# Anna --> B
# Bob --> C
# David --> A
# Simon --> C

Alternatively, we can use the items() method to access both the keys and values at the same time:

grades = {'John': 'B', 'Anna': 'B', 'Bob': 'C', 'David': 'A', 'Simon': 'C'}
for name, grade in grades.items():
print(name, '-->', grade)
# John --> B
# Anna --> B
# Bob --> C
# David --> A
# Simon --> C

Dictionary comprehension

Dictionary comprehension is a concise and efficient way to create and manipulate dictionaries in Python. It is similar to list comprehension, but it creates a dictionary instead of a list. With dictionary comprehension, you can create a dictionary in one line of code, rather than multiple lines using a for loop.

The syntax for dictionary comprehension is similar to list comprehension, but with curly braces {} instead of square brackets []. You specify the key and value expressions, separated by a colon, followed by the for clause. We can create, for instance, a dictionary that maps a number to its square:

squared_numbers = {x: x**2 for x in range(10)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

Dictionary comprehension can also include an if clause, similar to list comprehension, to filter the items included in the dictionary. We can modify the previous example to create the mapping from a number to its square for only even numbers:

squared_even_numbers = {x: x**2 for x in range(10) if x % 2 == 0}
# {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}

Dictionary comprehension can also be used to manipulate existing dictionaries. For example, the following dictionary comprehension creates a new dictionary that contains only the key-value pairs from an existing dictionary where the value is greater than 2:

original_dict = {1: 5, 2: 3, 3: 4, 4: 2}
filtered_dict = {k: v for k, v in original_dict.items() if v > 2}

These kinds of operations are especially useful when working with real-world data and tasks that need to perform data cleaning or filtering.

Real-World Examples of using Python Dictionaries

  1. Web Development: In web development, dictionaries can be used to store and organize data in the form of key-value pairs, such as form data submitted by users.
  2. Data Analysis: In data analysis, dictionaries can be used to store and organize data in the form of key-value pairs, such as data from a CSV file. They can also be used to store statistics such as the frequency of words in a text.
  3. Game Development: In game development, dictionaries can be used to store game state, such as the location of characters, items, and other game objects.
  4. Natural Language Processing: Dictionaries can be used to store and organize data in natural language processing, such as storing words and their meanings, or storing words and their synonyms.

What’s next?

--

--

Martin Mirakyan
Martin Mirakyan

Written by Martin Mirakyan

Software Engineer | Machine Learning | Founder of Profound Academy (https://profound.academy)

No responses yet