Search code examples
pythondictionarynestedyamlpretty-print

How to print a nested dictionary in YAML format


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!


Solution

  • 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.