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