如何将Python字典按列打印

1 投票
1 回答
3790 浏览
提问于 2025-04-18 18:26

假设我有一个字典,内容大致如下:

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

虽然这个结果离我想要的差不多,但我还是搞不定怎么让它对齐。你能想出一个方法来跟踪如何对齐这些值,然后再应用合适的缩进吗?

1 个回答

0

可以这样开始:

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中,输出的结果看起来是这样的,因为有括号的原因。但在你的电脑上应该看起来正常,因为你似乎是在用Python 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)

撰写回答