1

假设我有一本如下字典:

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

这正在接近我想要的,但我想不出一个让对齐工作的好方法。你能想出一种方法来跟踪如何对齐值然后应用适当的缩进吗?

4

1 回答 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 上,由于括号,输出看起来像这样,但它应该在您的计算机上看起来正确,因为它看起来像您在 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)
于 2014-08-25T16:25:40.473 回答