9 Amazing Python Dictionary Tricks You Didn’t Know

Ryk Kiel
4 min readFeb 11, 2023

--

Python dictionaries are a fundamental data structure in the Python programming language, providing fast and efficient key-value mapping capabilities. While dictionaries are a common topic in most Python tutorials, there are still many tricks and techniques that are not well known to many developers.

Here, we’ll explore nine amazing dictionary tricks that you may not have known you could do in Python. These tricks are bound to make your life easier and help you write cleaner and more efficient code.

Dictionary Comprehension

Dictionary comprehensions are a concise way to create new dictionaries based on existing dictionaries. This can be done by iterating over the keys and values of the original dictionary, and transforming them into a new dictionary with a single line of code.

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

Merging Dictionaries

Python provides several ways to merge dictionaries. One of the most straightforward ways is to use the update() method, which takes the contents of one dictionary and adds them to another. Alternatively, you can use the ** operator to merge two dictionaries.

d1 = {'a': 1, 'b': 2}
d2 = {'c': 3, 'd': 4}

d1.update(d2)
print(d1)
d3 = {**d1, **d2}
print(d3)
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
{'a': 1, 'b': 2, 'c': 3, 'd': 4}

Checking if a Key Exists in a Dictionary

In Python, you can use the in operator to check if a key exists in a dictionary. This is much faster than using the .get() method, which returns the value associated with a key or a default value if the key is not found.

squared = {x: x**2 for x in range(10)}
print(3 in squared)
print(11 in squared)
True
False

Sorting a Dictionary

Python dictionaries are unordered by default, but you can sort them by their keys or values. To sort a dictionary by its keys, use the sorted() function with the items() method of the dictionary. To sort a dictionary by its values, use the sorted() function with the items() method and a key function that returns the values.

squared = {x: x**2 for x in range(10)}

sorted_keys = sorted(squared.items(), key=lambda x: x[0])
print(sorted_keys)
sorted_values = sorted(squared.items(), key=lambda x: x[1])
print(sorted_values)
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49), (8, 64), (9, 81)]
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49), (8, 64), (9, 81)]

Finding the Maximum and Minimum

To find the maximum and minimum values in a dictionary, you can use the max() and min() functions with the values() method of the dictionary.

squared = {x: x**2 for x in range(10)}

maximum = max(squared.values())
print(maximum)
minimum = min(squared.values())
print(minimum)
81
0

Removing Keys from a Dictionary

You can use the pop() method to remove a key and its associated value from a dictionary. This method returns the value associated with the key that you passed as an argument.

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

# removed
{0: 0, 1: 1, 2: 4, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
9

Counting Occurrences of Elements

To count the occurrences of elements in a dictionary, you can use a dictionary comprehension. This is a great way to count the number of times each key appears in a list.

numbers = [1, 2, 3, 1, 2, 3, 4, 4, 4, 5, 5, 5, 5]
counts = {x: numbers.count(x) for x in set(numbers)}
print(counts)
{1: 2, 2: 2, 3: 2, 4: 3, 5: 4}

Flattening a Dictionary

To flatten a dictionary, you can use a for loop to iterate through the key-value pairs and create a new dictionary with the keys as the key and the values as the value.

original = {'a': {1: 'one', 2: 'two'}, 'b': {3: 'three', 4: 'four'}}
flattened = {}

for key, value in original.items():
flattened.update(value)
print(flattened)
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}

Sorting Dictionaries by Value

To sort a dictionary by its values, you can use the sorted() function with the items() method of the dictionary and a key function that returns the values.

squared = {x: x**2 for x in range(10)}
sorted_values = sorted(squared.items(), key=lambda x: x[1])
print(sorted_values)
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49), (8, 64), (9, 81)]

Conclusion

Dictionaries are a powerful and flexible data structure in Python. With these nine code snippets, you should now have a better understanding of how to use dictionaries in your code and take advantage of all the great things you can do with them.

Whether you are just starting out with Python or have been using it for a while, these tips and tricks will help you write better code and make the most of your time working with dictionaries.

Thanks for reading and happy coding! Feel free to follow for more.

--

--

Ryk Kiel

I am a Python lover with a love for problem-solving and creating solutions. I have expertise in web development, data analysis, and machine learning.