假设我有一本如下字典:
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
}
}
}
我希望能够在对齐的列中打印这个和其他不同深度的字典,如下所示:
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
我知道这种pprint
方法。它会产生这样的打印输出:
>>> 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'}}
这不是我想要的,不仅仅是因为它包含链括号和引号,还因为它没有将子值对齐到列中。
到目前为止,我的尝试如下:
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
))
这会产生以下结果:
>>> 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
这正在接近我想要的,但我想不出一个让对齐工作的好方法。你能想出一种方法来跟踪如何对齐值然后应用适当的缩进吗?