Dictionary 如何递归打印Python字典及其子字典,并将空格对齐到列中
我想创建一个函数,它可以接受一个字典的字典,如下所示Dictionary 如何递归打印Python字典及其子字典,并将空格对齐到列中,dictionary,printing,tabs,alignment,whitespace,Dictionary,Printing,Tabs,Alignment,Whitespace,我想创建一个函数,它可以接受一个字典的字典,如下所示 information = { "sample information": { "ID": 169888, "name": "ttH", "number of events": 124883, "cross section": 0.055519, "k factor": 1.0201, "generator": "pythia8",
information = {
"sample information": {
"ID": 169888,
"name": "ttH",
"number of events": 124883,
"cross section": 0.055519,
"k factor": 1.0201,
"generator": "pythia8",
"variables": {
"trk_n": 147,
"zappo_n": 9001
}
}
}
然后以如下简洁的方式打印,并使用空格对齐键和值:
sample information:
ID: 169888
name: ttH
number of events: 124883
cross section: 0.055519
k factor: 1.0201
generator: pythia8
variables:
trk_n: 147
zappo_n: 9001
我对该函数的尝试如下:
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
))
sample information:
name: ttH
generator: pythia8
cross section: 0.055519
variables:
zappo_n: 9001
trk_n: 147
number of events: 124883
k factor: 1.0201
ID: 169888
它产生如下输出:
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
))
sample information:
name: ttH
generator: pythia8
cross section: 0.055519
variables:
zappo_n: 9001
trk_n: 147
number of events: 124883
k factor: 1.0201
ID: 169888
如图所示,它成功地递归打印了字典字典,但是它没有将值对齐到一个整洁的列中。对于任意深度的词典,有什么合理的方法可以做到这一点?尝试使用该模块。您可以这样做,而不是编写自己的函数:
import pprint
pprint.pprint(my_dict)
请注意,这将在字典周围打印{和}等字符,在列表周围打印[],但如果可以忽略它们,pprint将为您处理所有嵌套和缩进