The open blogging platform. Say no to algorithms and paywalls.

16 Intermediate-Level Python Dictionary Tips Tricks and Shortcuts

Dictionaries are the heart and soul of Python. Here are the most essential tips and tricks for you to use with dictionaries.

The following code snippets are available on Github as Gists, and were tested with Python 3.7. This is a companion article to: Learn Programming with Python — Introduction to Compound Data Types: Dictionaries *Dictionaries are a very versatile compound data type, allowing us to create mappings between keys and values…*

1. Print All the Key: Value Pairs in a Nested Dictionary

This is a recursive solution to printing all k:v pairs in a dictionary. It handles the presence of lists, sets and tuples in a value.

This is the output produced:


2. Sort a Dictionary

Since Python3.6, dictionaries retain insertion order by default. However, dictionaries don’t support sorting.

It is possible to get an Iteratable sequence of the dictionary’s k:v pairs as a sequence of tuples. And then convert that list of sorted tuples back to a dictionary — the insertion order is retained.

3. Merge Two Dictionaries

From python version 3.9, the merge operator | is available for dictionaries. Until then, you can use the shallow copy merge method.

4. Make a Dictionary from Two Lists

We can zip the two lists to form a sequence of tuples, and pass this to the dict() constructor.

5. Get all Items in a Nested Dictionary by Key

Here we’re using recursion again. Note: there are good Python libraries available if you prefer to use path expressions. See: JMES Path.

6. Get all Items in a Nested Dictionary by Value

Unsurprisingly, this is very similar to the previous example. Note the use of yield to create an iterator. Line 32 coerces all of the individual yield executions into a list.

7. Create a Dictionary using Dictionary Comprehension

Dictionary comprehension uses the {key: value} construct with a for loop over a sequence.

8. Use Default Values for New Items

The defaultdict is very useful when you want to append values to an existing key, instead of overwriting it. Normally, line #9 would give an error because the value in this key would not be a list, it would be None. so we wouldn’t be able to append.

9. Convert List of Tuples to Dictionary

Again using a defaultdict, this time the default value is a dictionary.

10. Create a Dictionary from a CSV File with Column Headers

Let’s not reinvent the wheel, and instead use the CSV module.

11. Delete an Item from a Dictionary

Use the pop() method to delete a dictionary item and retrieve its value.

12. Make a Deep Copy of a Dictionary

Use the deepcopy function in the copy module to make a true copy of a dictionary containing mutable objects, such as a list.

13. Reverse Keys and Values

Maybe you will need to do this one day! This solution uses a dictionary comprehension.

14. Save Multiple Dictionaries to a File

As an alternative to using pickle to save one object to one file, here we are using shelve to store multiple objects in a file.

15. Convert from Dictionary to JSON

Nothing could be simpler! We saw some simple examples at #6 and #10. Unless your dictionary object contains user-defined classes, datetime objects, set or other Python objects…

In this case, we will subclass the JSONEncoder object and handle our special cases differently.

On line #12 I’m using “duck typing”. The idea is to see if the object behaves like an iterable sequence, if so then convert it to a list. If the object doesn’t behave like an iterable, then an exception is raised (which we ignore on line #16).

16. Delete Multiple Items from a Dictionary During Iteration

In python3, the items() method returns an iterator. Trying to delete an item results in a RuntimeError.

We can avoid the RuntimeError by temporarily making a note of the keys all the items we mark for deletion.

This example simply removes all items whose value is an even number.

I hope you enjoyed this! Please be sure to leave a comment if you find any mistakes!

Continue Learning