[英]how to print a Python dictionary in columns
假設我有一個類似以下的字典:
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
這正在接近我想要的,但是我找不到使對齊工作正常的好方法。 您能想到一種方法來跟蹤如何對齊值,然后應用適當的縮進嗎?
這樣的事情如何開始:
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])
在Python 2.7上,由於括號,輸出看起來像這樣,但是在計算機上看起來應該正確,因為看起來就像在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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.