Python dictionaries are incredibly powerful data structures — in this post, you’ll learn seven techniques to help you master them!
Let’s get started.
Since Python 3.5, it’s been possible to easily merge two dictionaries, using **kwargs:
Beginning in Python 3.9, you can use the union operator (|) to combine two dictionaries:
To see if a key exists in a dictionary, you can use the in keyword.
For example, let’s see if some keys exist in a dictionary:
To easily remove a dictionary, you can use the pop function. The pop function returns the value of the key being removed.
Pop accepts two arguments (key to drop, default value if key is not found).
Let’s try dropping some items:
The last print statement returns an error as the key doesn’t exist and no default value is provided.
Python Dictionary Comprehensions can allow you to easily iterate over both the key and the value.
An easy-to-explain example to demonstrate this would be to build a dictionary where the key is a number and the value is the number squared:
Learn more about dictionary comprehensions in this in-depth post!
Let’s use a list comprehension to remove all empty items from a dictionary. An item is considered empty when it has a None value.
To access a Python dictionary item, you can use square bracket notation. This works well — until it doesn’t.
If a key doesn’t exist in a dictionary, an AttributeError is thrown.
This can disrupt your code.
However, using the get method will simply return None:
Say you have a dictionary of people’s heights and you wanted to filter out anyone below a certain height.
You could do this with a for loop or (much easier) with a dictionary comprehension.
Let’s filter out anyone less than 170cm.
Thanks for reading! In this tutorial, you learned 7 techniques for Python dictionaries.
If you’re interested in mastering Python Lists, check out my other tutorial here: