1

Let's say I have a dictionary like the following:

dictionary1 = {
    "Scientology": {
        "source": "LRH",
        "scilon 1": {
            "name": "John Travolta",
            "OT level": 5,
            "wall of fire": True
        },
        "scilon 2": {
            "name": "Tom Cruise",
            "OT level": 6,
            "wall of fire": True
        }
    }
}

I want to be able to print this and other dictionaries of varying depths in aligned columns like the following:

Scientology:
    source: LRH
    scilon 1:
        name:         John Travolta
        OT level:     5
        wall of fire: True
    scilon 2:
        name          Tom Cruise
        OT level:     6
        wall of fire: True

I am aware of the pprint approach. It produces a printout like this:

>>> pprint.pprint(dictionary1)
{'Scientology': {'scilon 1': {'OT level': 5,
                              'name': 'John Travolta',
                              'wall of fire': True},
                 'scilon 2': {'OT level': 6,
                              'name': 'Tom Cruise',
                              'wall of fire': True},
                 'source': 'LRH'}}

This is not what I want, not simply because it includes the chain brackets and quotation marks, but because it does not align the sub-values into columns.

My attempt so far is as follows:

def printDictionary(
    dictionary = None,
    indentation = ''
    ):
    for key, value in dictionary.iteritems():
        if isinstance(value, dict):
            print("{indentation}{key}:".format(
            indentation = indentation,
            key = key
        ))
            printDictionary(
                dictionary = value,
                indentation = indentation + '   '
            )
        else:
            print(indentation + "{key}: {value}".format(
                key = key,
                value = value
            ))

This produces the following:

>>> printDictionary(dictionary1)
Scientology:
   scilon 2:
      OT level: 6
      name: Tom Cruise
      wall of fire: True
   source: LRH
   scilon 1:
      OT level: 5
      name: John Travolta
      wall of fire: True

This is approaching what I want, but I can't figure a good way to get the alignment working. Can you think of a way of keeping track of how to align the values and then applying the appropriate indentation?

d3pd
  • 7,935
  • 24
  • 76
  • 127

1 Answers1

0

How about something like this to start:

dic = {
    "Scientology": {
        "source": "LRH",
        "scilon 1": {
            "name": "John Travolta",
            "OT level": 5,
            "wall of fire": True
        },
        "scilon 2": {
            "name": "Tom Cruise",
            "OT level": 6,
            "wall of fire": True
        }
    }
}


for key1 in dic:
    print(key1,":")
    for key2 in dic[key1]:
        if type(dic[key1][key2]) is dict:
            print("\t", key2, ":")
            for key3 in dic[key1][key2]:
                print("\t\t", key3, ":", dic[key1][key2][str(key3)])
        else:
            print("\t", key2, ":", dic[key1][key2])

On Python 2.7 the output looks like this because of the brackets, but it should look right on your computer because it looks like you're on 3.

('Scientology', ':')
('\t', 'scilon 2', ':')
('\t\t', 'OT level', ':', 6)
('\t\t', 'name', ':', 'Tom Cruise')
('\t\t', 'wall of fire', ':', True)
('\t', 'source', ':', 'LRH')
('\t', 'scilon 1', ':')
('\t\t', 'OT level', ':', 5)
('\t\t', 'name', ':', 'John Travolta')
('\t\t', 'wall of fire', ':', True)
Charles Clayton
  • 17,005
  • 11
  • 87
  • 120
  • Thanks very much for your suggestion. Unfortunately, I need to be able to deal with dictionaries of varying depths. That's why the function I wrote is recursive. – d3pd Aug 27 '14 at 16:07