Home > Back-end >  How can I convert a nested dictionary to a table in python
How can I convert a nested dictionary to a table in python

Time:11-09

Suppose I have a nested dictionaries like chapters and sections of a book (a balanced tree structure). I want to convert it to a table where each branch is a row, and keys are values in addition to leaves' values.

{
  "A1": {
      "A1-1": {
        "A1-1-1": "0.2028",
        "A1-1-2": "0.1901",
      },
      "A1-2": {
        "A1-2-1": "0.1951",
        "A1-2-2": "0.1806",
      },
   },
   "A2" {

             ...

Like:

A1   A1-1  A1-1-1 0.2028
A1   A1-1  A1-1-2 0.1901
A1   A1-2  A1-2-1 0.1951

I tried to use json_normalize(data) but it just gives 1 rows and some nested column headings.

CodePudding user response:

You can use some recursive processing:

def superitems(obj):
    if isinstance(obj, dict):
        for k, v in obj.items():
            for i in superitems(v):
                yield (k,)   i
    else:
        yield (obj,)
 
[*superitems(data)]
# [('A1', 'A1-1', 'A1-1-1', '0.2028'), 
#  ('A1', 'A1-1', 'A1-1-2', '0.1901'), 
#  ('A1', 'A1-2', 'A1-2-1', '0.1951'), 
#  ('A1', 'A1-2', 'A1-2-2', '0.1806')]

This, you can use for any output:

print("\n".join(map("\t".join, superitems(data))))
A1  A1-1    A1-1-1  0.2028
A1  A1-1    A1-1-2  0.1901
A1  A1-2    A1-2-1  0.1951
A1  A1-2    A1-2-2  0.1806

CodePudding user response:

  1. You need to first flatten the dictionary, I found this code, but I couldn't find the attribution for it; but it works:
def flatten(d, c = []):
   for a, b in d.items():
      yield from([c   [a, b]]
         if not isinstance(b, dict)
         else flatten(b, c   [a]))
  1. Use tabulate to generate your output table in the format you desired
dict = {....}
output = list(flatten(dict))
print(tabulate(output))
  • Related