In this post, we’ll look at 4 different ways to flatten a dict in Python. For each method I’ll point out the pros and cons, and I'll give a quick performance analysis. For this tutorial, I ran all examples on Python 3.7.

 

Why Should You Know How to Flatten a Dict in Python?

There are many reasons you would need a flattened dictionary. One is that it makes it simpler to compare two dicts. The other is that it’s easier to navigate and manipulate it, since a flat structure is one level deep.

Python is a versatile language, meaning you can achieve the same goals in several ways. Choosing the best solution for a problem requires weighting the benefits of one solution over another.

The goal of this post is to provide you many options for this problem and give you as much data as possible so you can make an informed decision. So, let’s go.

PS: If you don’t have Python 3.7 you can install it using pyenv and even have multiple versions at the same time with no conflict.

Table of Contents

  1. Using your Own Recursive Function
  2. Using your Own Recursive Function + Generators
  3. Using pandas json_normalize
  4. Using the flatdict Library
  5. Conclusion

#python 

4 Different Ways to Flatten a Dictionary in Python
2.90 GEEK