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?