-1

Given a dictionary with dictionaries inside it, I want to print all the content one by one. For example, the dictionary is:

data = {'school': 'abc college',
 'class': {'A': 30, 'B': 25, 'C': 10},
 'student': {'A': {'Peter': 'boy'},
  'B': {'Mary': 'girl'},
  'C': {'Charles': 'boy'}}}

I want to print it as:

school: abc college
class:
    A: 30
    B: 25
    C: 10
student:
    A:
        Peter: boy
    B:
        Mary: girl
    C: 
        Charles: boy

That means if there is a dictionary inside a dictionary, I would like to print the deepest level dictionary first before proceeding to the next element, similar to the sequence of a depth-first-search.

However, the levels of the dictionary is not known beforehand, so it seems that for loop is not a good way. I also tried iter but dictionary is not iterable. I wonder how I can achieve that. Thanks!

Georgy
  • 12,464
  • 7
  • 65
  • 73
Mayan
  • 492
  • 4
  • 11
  • here [it](https://stackoverflow.com/questions/3229419/how-to-pretty-print-nested-dictionaries) may help – Alexander Lekontsev May 27 '20 at 10:17
  • @AlexanderLekontsev, my ultimate goal is to record the data in some files. I simplified the description here. – Mayan May 27 '20 at 10:18
  • You can also use `json` library, and do json.dumps(data, indent=4) – Shivam Seth May 27 '20 at 10:22
  • Does this answer your question? [pprint dictionary on multiple lines](https://stackoverflow.com/questions/20171392/pprint-dictionary-on-multiple-lines) – Shivam Seth May 27 '20 at 10:27
  • A really elegant recursive solution to finding the depth of dictionary can be found [here](https://stackoverflow.com/a/23499101/3595907) – DrBwts May 27 '20 at 10:28
  • Does this answer your question? [Know the depth of a dictionary](https://stackoverflow.com/questions/23499017/know-the-depth-of-a-dictionary) – DrBwts May 27 '20 at 10:40
  • 1
    Does this answer your question? [How to pretty print nested dictionaries?](https://stackoverflow.com/questions/3229419/how-to-pretty-print-nested-dictionaries) Especially see this answer using YAML: https://stackoverflow.com/a/14892136/7851470 – Georgy May 27 '20 at 11:06
  • My goal is not to print a neat nested dictionary. My goal is to do something on each element in the dictionary. I think @Andra's idea guided me to achieve the task. thanks – Mayan May 28 '20 at 00:57

3 Answers3

3

This problem is a good opportunity to use recursion: whenever we encounter a value that is dictionary, we will call the function again on this dict.

def recursive_print_dict( d, indent = 0 ):
    for k, v in d.items():
        if isinstance(v, dict):
            print("\t" * indent, f"{k}:")
            recursive_print_dict(v, indent+1)
        else:
            print("\t" * indent, f"{k}:{v}")
1

You should solve this problem by making a recursive function.

You have to iterate through the keys of the dictionary and check if the value is also a dict. If so, call the function on that value, else you just print those values and continue iterating.

1

if all you want is pretty printing you can try pprint

In [2]: from pprint import pprint

In [3]: data = {'school': 'abc college',
   ...:  'class': {'A': 30, 'B': 25, 'C': 10},
   ...:  'student': {'A': {'Peter': 'boy'},
   ...:   'B': {'Mary': 'girl'},
   ...:   'C': {'Charles': 'boy'}}}

In [4]: pprint(data)
{'class': {'A': 30, 'B': 25, 'C': 10},
 'school': 'abc college',
 'student': {'A': {'Peter': 'boy'},
             'B': {'Mary': 'girl'},
             'C': {'Charles': 'boy'}}}

if you really want to do it from scratch you write a recursive function

In [5]: data = {'school': 'abc college',
   ...:  'class': {'A': 30, 'B': 25, 'C': 10},
   ...:  'student': {'A': {'Peter': 'boy'},
   ...:   'B': {'Mary': 'girl'},
   ...:   'C': {'Charles': 'boy'}}}

In [6]: def pp(_dict, padding=""):
   ...:     val_str = []
   ...:     for k, v in _dict.items():
   ...:         if type(v) == dict:
   ...:             val_str.append("{padding}{key}:\n{val_str}".format(padding=padding, key=k, val_str=pp(v, padding+" ")))
   ...:         else:
   ...:             val_str.append("{padding}{key}: {val}".format(padding=padding, key=k, val=v))
   ...:     return "\n".join(val_str)
   ...:

In [7]: print(pp(data))
school: abc college
class:
 A: 30
 B: 25
 C: 10
student:
 A:
  Peter: boy
 B:
  Mary: girl
 C:
  Charles: boy

In [8]:
mojozinc
  • 164
  • 8