如何以递归方式将Python字典及其子字符串与空格对齐打印到列中

时间:2014-08-12 14:58:07

标签: 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",
        "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

如图所示,它成功地以递归方式打印字典字典,但不会将值与整齐的列对齐。对于任意深度的词典,这样做的合理方法是什么?

1 个答案:

答案 0 :(得分:0)

尝试使用pprint模块。您可以这样做,而不是编写自己的函数:

import pprint
pprint.pprint(my_dict)

请注意,这会在您的词典周围打印{}等字符,并在您的列表周围[]打印,但如果您可以忽略它们,pprint()将会占用照顾你所有的筑巢和缩进。