The world’s leading publication for data science, AI, and ML professionals.

5 Expert Tips to Skyrocket Your Dictionary Skills in Python 🚀

Think you understand dictionaries in Python?

GAIN VALUABLE SKILLS

Photo by Danylo Suprun on Unsplash
Photo by Danylo Suprun on Unsplash

Overview of Your Journey


Setting the Stage

The dictionary is one of the fundamental data structures in Python. You use it for counting, grouping, and expressing relations. Yet, not everyone knows how to effectively use dictionaries.

Poor use of dictionaries often leads to lengthy code, slow code, and even subtle bugs 😧

When I started out with Python, I could barely access and retrieve data from a dictionary. But after a few years, I’ve come to realize that having a good grasp of dictionaries is vital.

In the words of one of the core developers of Python:

There are two kinds of people in the world: People who have mastered dictionaries and total goobers. – Raymond Hettinger

Don’t be a goober! In this blog, I will show you 5 tips to take your dictionary skills in Python to the level of professionals 🔥


Quick Recap – The Basics

The standard way to create dictionaries is with the syntax:

# Creating an empty dictionary
empty_dict = {}
# Standard way to create a dictionary
better_call_saul = {"Jimmy": 33, "Kim": 31, "Gus": 44}
# Can use the dictionary constructor function
better_call_saul = dict([("Jimmy", 33), ("Kim", 31), ("Gus", 44)])

In the code above:

  • The names Jimmy, Kim, and Gus are the keys of the dictionary.
  • The ages 33, 31, and 44 are the values of the dictionary.
  • The pairs "Jimmy": 33, "Kim": 31, and "Gus": 44 are key-value pairs.

You can access values from the dictionary better_call_saul with the syntax

# Getting Kim's age
print(better_call_saul["Kim"])
Output: 31
# Setting Jimmy's age
better_call_saul["Jimmy"] = 34

As you can see from the above code, dictionaries are mutable. The keys in the dictionary also have to be distinct.

You can add or remove key-value pairs effortlessly with dictionaries:

# Setting a new key-value pair
better_call_saul["Jonathan"] = 54
# Removing the key-value pair again (sorry Jonathan!)
del better_call_saul["Jonathan"]

Finally, not every Python object can be a key in a dictionary. The precise rule is that the object should be hashable. Rest assured that any immutable object is hashable. For a more in-depth explanation of hashable, check out the blog:

3 Essential Questions About Hashable in Python


Tip 1 – Iteration with Dictionaries

The first thing you should know is that, as of Python version 3.7, dictionaries are ordered:

When you print a dictionary or loop through its elements, you will see the elements in the same order in which they were added to the dictionary – Eric Matthes, Python Crash Course

Iterate Through the Keys

To iterate through the keys of a dictionary, you can use the method keys():

better_call_saul = {"Jimmy": 33, "Kim": 31, "Gus": 44}
for name in better_call_saul.keys():
    print(name)
Output: 
Jimmy
Kim
Gus

As you can see, by using the keys() method you get access to the keys of the dictionary. But wait! It is also possible to write:

for name in better_call_saul:
    print(name)
Output: 
Jimmy
Kim
Gus

If you iterate through the dictionary, then it will be default iterate through the keys 😎

Iterate Through the Values

If you want to iterate through the values of a dictionary, then you should use the values() method:

better_call_saul = {"Jimmy": 33, "Kim": 31, "Gus": 44}
# Calculating the total age of the characters
total = 0
for age in better_call_saul.values():
    total += age
print(total)
Output:
108

Iterate Through Both the Keys and Values

If you need both the keys and the values in an iteration, then you should use the items() method. Let us first check out what it returns:

print(better_call_saul.items())
Output:
dict_items([('Kim', 31), ('Gus', 44)])

The output is a dict_items object. Such objects function the same way as a list of tuples. Thus you can use the syntax:

better_call_saul = {"Jimmy": 33, "Kim": 31, "Gus": 44}
for name, age in better_call_saul.items():
    print(f"{name} is {age} years old.")
Output:
Jimmy is 33 years old.
Kim is 31 years old.
Gus is 44 years old.

Tip 2 – Getting Values with Confidence

Consider the code:

better_call_saul = {"Jimmy": 33, "Kim": 31, "Gus": 44}
young_guy_age = better_call_saul["Nacho"]
Result:
KeyError: 'Nacho'

You get a KeyError because the key "Nacho" doesn’t exist in the dictionary better_call_saul. Oops 😬

This is actually pretty realistic. Often you don’t have complete control over what is in your dictionary. The data in your dictionary could come from

  • web scraping,
  • an API,
  • or loading data.

Having your program crash this easily is going to cause you a world of pain. Instead, you can use the get() method:

young_guy_age = better_call_saul.get("Nacho", "Can't find")
print(young_guy_age)
Output:
Can't find

The get() method takes two arguments:

  1. The key for which you want to retrieve the corresponding value.
  2. The default value in case the key does not exist in the dictionary.

If you don’t provide a second argument to the get() method, then the second argument is by default None. Using the get() method will make your code more robust by avoiding loads of KeyErrors.

Hint: A related method to get() is the [setdefault](https://www.programiz.com/python-programming/methods/dictionary/setdefault)() method. Both methods are awesome, and you should take a look at setdefault as well.


Tip 3 – Dictionary Comprehensions

You probably know about list comprehensions. List comprehensions are a Pythonic way of building lists. You use them as a powerful alternative to standard loops:

# Gives the square numbers from 0 to 9
squares = []
for num in range(10):
    squares.append(num ** 2)
# List comprehensions do the same thing!
squares = [num ** 2 for num in range(10)]

Did you know that Python also supports dictionary comprehensions? If you want a quick way to build a dictionary, then look no further:

# Manually making a squares dictionary
squares = {0:0, 1:1, 2:4, 3:9, 4:16, 5:25, 6:36, 7:49, 8:64, 9:81}
# Dictionary comprehensions do the same thing!
squares = {num: num ** 2 for num in range(10)}

As another example, consider a list of names:

names = ["Jimmy", "Kim", "Gus"]

Say you want to construct a dictionary where:

  • The keys of the dictionary are the names in the list names.
  • The values of the dictionary are the lengths of the names.

You can do this in a single line with dictionary comprehensions!

length_of_names = {name: len(name) for name in names}
print(length_of_names)
Output:
{'Jimmy': 5, 'Kim': 3, 'Gus': 3}

Tip 4 – Using the Zip Function

A common problem is having two separate lists that you want to combine into a dictionary. As an example, say you have the following two lists:

names = ["Jimmy", "Kim", "Gus"]
ages = [33, 31, 44]

How can you combine names and ages to form the dictionary better_call_saul from before? Before I show you the magic trick, let’s verify that a straightforward approach works:

# The "enumerate" approach
better_call_saul = {}
for idx, name in enumerate(names):
    better_call_saul[name] = ages[idx]

Not bad! The enumerate function is often useful in such cases.

Yet, there is an even more slick way of doing this: Use the zip function with the dict constructor!

# The "zip" approach
better_call_saul = dict(zip(names, ages))

The zip function works like a zipper on a jacket – It pairs up objects from beginning to end.

The value zip(names, ages) is a zip object, so it is not that easy to understand. But if you turn it into a list, then it becomes more tractable:

print(list(zip(names, ages)))
Output:
[('Jimmy', 33), ('Kim', 31), ('Gus', 44)]

This looks like something the dict constructor can eat! You don’t even need to turn the zip object into a list before using the dict constructor 😍

Fun Fact: The "zip" approach is significantly faster than the "enumerate" approach in terms of execution speed.


Tip 5 – Dictionary Merging

It is sometimes necessary to merge two dictionaries. Dictionary merging combines the elements from two dictionaries into a single dictionary.

There are many ways to do dictionary merging in Python:

  • I will show you one traditional way of doing dictionary merging by using the update() method.
  • I will show you the awesome dictionary merging operators introduced in Python 3.9.

Merging with the Update Method

Let’s say that you have the two dictionaries:

better_call_saul = {"Jimmy": 33, "Kim": 31, "Gus": 44}
breaking_bad = {"Walter": 46, "Jesse": 23, "Jimmy": 38}

If you want to merge the dictionaries, then you can use the update() method:

# Updates better_call_saul
better_call_saul.update(breaking_bad)
print(better_call_saul)
Output:
{'Jimmy': 38, 'Kim': 31, 'Gus': 44, 'Walter': 46, 'Jesse': 23}

You have now updated better_call_saul with the new information from breaking_bad. Notice that the key "Jimmy" has the value 38. The previous value 33 has been overridden.

Merging with the Dictionary Merging Operator (Python 3.9+)

In Python 3.9 the dictionary merging operators | and |= were introduced. Both of them simplifies dictionary merging. If you again have the dictionaries better_call_saul and breaking_bad from before

better_call_saul = {"Jimmy": 33, "Kim": 31, "Gus": 44}
breaking_bad = {"Walter": 46, "Jesse": 23, "Jimmy": 38}

then you can write:

better_call_saul |= breaking_bad
print(better_call_saul)
Output:
{'Jimmy': 38, 'Kim': 31, 'Gus': 44, 'Walter': 46, 'Jesse': 23}

The operator |= is the in-place dictionary merging operator. It modifies the dictionaries in place. You can use the dictionary merging operator | if you want a new dictionary with the merged content:

better_call_saul = {"Jimmy": 33, "Kim": 31, "Gus": 44}
breaking_bad = {"Walter": 46, "Jesse": 23, "Jimmy": 38}
gilligan_universe = better_call_saul | breaking_bad
print(gilligan_universe)
Output:
{'Jimmy': 38, 'Kim': 31, 'Gus': 44, 'Walter': 46, 'Jesse': 23}

The new syntax introduced in Python 3.9 is great if you have more than two dictionaries to merge.


Wrapping Up

You can now approach future projects with the swagger of someone who understands dictionaries!

Photo by Nathan Dumlao on Unsplash
Photo by Nathan Dumlao on Unsplash

Like my writing? Check out my blog posts Type Hints, Formatting with Black, and Underscores in Python for more Python content. If you are interested in data science, Programming, or anything in between, then feel free to add me on LinkedIn and say hi ✋


Related Articles