入れ子になった辞書をきれいに印刷する方法は?


289

Pythonで深さ〜4の辞書をきれいに印刷するにはどうすればよいですか?でかなりの印刷を試みましたpprint()が、うまくいきませんでした:

import pprint 
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(mydict)

"\t"ネストごとにインデント()が必要なので、次のようになります。

key1
    value1
    value2
    key2
       value1
       value2

これどうやってするの?


29
「動作しなかった」とはどういう意味ですか?pprintが「機能しなかった」方法を非常に正確に指定してください。
S.Lott、2007

5
私はこれらの回答のうち3つを使用しました(特定のシナリオではそれぞれ良い):@Kenのjson回答は良いですが、オブジェクトをjsonシリアライズできない場合(例外をスローする)に失敗することがあります。@Kenのjsonの回答が機能しない場合は、@ Andyのyamlの回答を試してみてください。機能するはずですが、文字列の出力は人間が読める形式ではありません。[@sthの答え]が最も一般的です(任意のオブジェクトで機能し、ライブラリを使用しません)。
Trevor Boyd Smith

回答:


143

書式をどのようにしたいのか正確にはわかりませんが、次のような関数から始めることができます。

def pretty(d, indent=0):
   for key, value in d.items():
      print('\t' * indent + str(key))
      if isinstance(value, dict):
         pretty(value, indent+1)
      else:
         print('\t' * (indent+1) + str(value))

8
@Kenの従来の答えはこれよりもはるかに優れています。JSONはすでにすべてを処理しており、これにより次のようなエラーが発生する可能性があります。UnicodeEncodeError : 'ascii' codec't encode character u '\ xf3' in position 50:ordinal not range(128)
wonderwhy

それは私にUnicodeEncodeErrorを与えたので、それは私のソリューションのネストされたdictで動作するようにすることはできません。また、dictキーを出力せず、リストとタプル内に移動せず、Pythonの有効な構文を維持しません。
y.petremann 2014年

この答えは私にとっては魅力的なものでしたが、出力する値の数に制限を設定する新しい質問stackoverflow.com/questions/36972225/…を投稿しました。
gsamaras 2016年

かなり良い。OPの質問のようにネストされたリストがある場合は、そのための処理を追加する必要があります。Py2で問題が発生している場合は__future__、答えが今述べているようなハックなしではUnicodeを適切に処理できないため、必要に応じてそれらを使用する必要があります(またはすでに3に更新します)。
sudo 2018

これは私のために十分によく働い: python def pretty(d, indent=0): for key, value in d.items(): if isinstance(value, dict): print(' ' * indent + str(key)) pretty(value, indent+1) else: print(' ' * (indent+1) + f"{key}: {value}")
hum3

500

私の最初の考えは、JSONシリアライザーはおそらくネストされたディクショナリーにかなり優れているということでした。

>>> import json
>>> print json.dumps({'a':2, 'b':{'x':3, 'y':{'t1': 4, 't2':5}}},
...                  sort_keys=True, indent=4)
{
    "a": 2,
    "b": {
        "x": 3,
        "y": {
            "t1": 4,
            "t2": 5
        }
    }
}

40
これはクールですが、すべての辞書をうまく印刷できません。print json.dumps(myObject .__ dict__、sort_keys = True、indent = 4)#TypeError:<object at 0x0000000002E6A748> not JSON
JSONizable

4
これは便利に見えますが、その出力はOPが望んだものではありません。
martineau 2013年

2
@martineau:OPが要求する出力は意味をなさず、辞書は値ごとにキーを必要とします。
naught101 2013年

2
@ naught101:プリティプリンターは、必要な出力を生成するために必要なことを何でも実行できます。
martineau 2013年

22
json.dumpsは変換関数をオプションの引数として取るため、json.dumps(myObject .__ dict__、sort_keys = True、indent = 4、deault = str)を使用すると、少なくともreprのオブジェクト実装を使用して、それ自体を印刷して丸めることができます'not JSON serializable' TypeError
RFairey

56

PyYAMLを介してYAMLを試すことができます。出力は微調整できます。私は以下から始めることをお勧めします:

print yaml.dump(data, allow_unicode=True, default_flow_style=False)

結果は非常に読みやすいです。必要に応じて、解析してPythonに戻すこともできます。

編集:

例:

>>> import yaml
>>> data = {'a':2, 'b':{'x':3, 'y':{'t1': 4, 't2':5}}}
>>> print yaml.dump(data, default_flow_style=False)
a: 2
b:
  x: 3
  y:
    t1: 4
    t2: 5

1
yamlを使用することは非常に興味深いものです。フォーマットよりもデータ型が保持されるからです。私がそれに対して言えることは、有効なpython文字列を生成しないが、ほとんどpythonに変換できるということです。
y.petremann 2014年

1
yamlはNumpyのバージョンのスカラー型が好きではありません... numpy配列をサポートしていないことは驚くに値しませんが、a floatとaで同じ出力が期待されますnumpy.float64
PhilMacKay

このアプローチは、辞書のリストを使用して私にも
Grant Shannon

36

何が行われたかに関して、非常に単純なフォーマットでpythonインタープリターの出力を少なくとも模倣するきれいなプリンターは見当たらないので、これが私のものです。

class Formatter(object):
    def __init__(self):
        self.types = {}
        self.htchar = '\t'
        self.lfchar = '\n'
        self.indent = 0
        self.set_formater(object, self.__class__.format_object)
        self.set_formater(dict, self.__class__.format_dict)
        self.set_formater(list, self.__class__.format_list)
        self.set_formater(tuple, self.__class__.format_tuple)

    def set_formater(self, obj, callback):
        self.types[obj] = callback

    def __call__(self, value, **args):
        for key in args:
            setattr(self, key, args[key])
        formater = self.types[type(value) if type(value) in self.types else object]
        return formater(self, value, self.indent)

    def format_object(self, value, indent):
        return repr(value)

    def format_dict(self, value, indent):
        items = [
            self.lfchar + self.htchar * (indent + 1) + repr(key) + ': ' +
            (self.types[type(value[key]) if type(value[key]) in self.types else object])(self, value[key], indent + 1)
            for key in value
        ]
        return '{%s}' % (','.join(items) + self.lfchar + self.htchar * indent)

    def format_list(self, value, indent):
        items = [
            self.lfchar + self.htchar * (indent + 1) + (self.types[type(item) if type(item) in self.types else object])(self, item, indent + 1)
            for item in value
        ]
        return '[%s]' % (','.join(items) + self.lfchar + self.htchar * indent)

    def format_tuple(self, value, indent):
        items = [
            self.lfchar + self.htchar * (indent + 1) + (self.types[type(item) if type(item) in self.types else object])(self, item, indent + 1)
            for item in value
        ]
        return '(%s)' % (','.join(items) + self.lfchar + self.htchar * indent)

初期化するには:

pretty = Formatter()

定義された型のフォーマッタの追加をサポートできます。このような関数を作成し、set_formaterで目的の型にバインドするだけです。

from collections import OrderedDict

def format_ordereddict(self, value, indent):
    items = [
        self.lfchar + self.htchar * (indent + 1) +
        "(" + repr(key) + ', ' + (self.types[
            type(value[key]) if type(value[key]) in self.types else object
        ])(self, value[key], indent + 1) + ")"
        for key in value
    ]
    return 'OrderedDict([%s])' % (','.join(items) +
           self.lfchar + self.htchar * indent)
pretty.set_formater(OrderedDict, format_ordereddict)

歴史的な理由で、私はクラスではなく関数であった以前のきれいなプリンターを保持していますが、どちらも同じように使用でき、クラスバージョンではさらに多くのことが許可されます。

def pretty(value, htchar='\t', lfchar='\n', indent=0):
    nlch = lfchar + htchar * (indent + 1)
    if type(value) is dict:
        items = [
            nlch + repr(key) + ': ' + pretty(value[key], htchar, lfchar, indent + 1)
            for key in value
        ]
        return '{%s}' % (','.join(items) + lfchar + htchar * indent)
    elif type(value) is list:
        items = [
            nlch + pretty(item, htchar, lfchar, indent + 1)
            for item in value
        ]
        return '[%s]' % (','.join(items) + lfchar + htchar * indent)
    elif type(value) is tuple:
        items = [
            nlch + pretty(item, htchar, lfchar, indent + 1)
            for item in value
        ]
        return '(%s)' % (','.join(items) + lfchar + htchar * indent)
    else:
        return repr(value)

それを使用するには:

>>> a = {'list':['a','b',1,2],'dict':{'a':1,2:'b'},'tuple':('a','b',1,2),'function':pretty,'unicode':u'\xa7',("tuple","key"):"valid"}
>>> a
{'function': <function pretty at 0x7fdf555809b0>, 'tuple': ('a', 'b', 1, 2), 'list': ['a', 'b', 1, 2], 'dict': {'a': 1, 2: 'b'}, 'unicode': u'\xa7', ('tuple', 'key'): 'valid'}
>>> print(pretty(a))
{
    'function': <function pretty at 0x7fdf555809b0>,
    'tuple': (
        'a',
        'b',
        1,
        2
    ),
    'list': [
        'a',
        'b',
        1,
        2
    ],
    'dict': {
        'a': 1,
        2: 'b'
    },
    'unicode': u'\xa7',
    ('tuple', 'key'): 'valid'
}

他のバージョンと比較して:

  • このソリューションはオブジェクトタイプを直接検索するため、リストや辞書だけでなく、ほぼすべてをきれいに印刷できます。
  • 依存関係はありません。
  • すべてが文字列の中に置かれているので、あなたはそれを使って何でも好きなことができます。
  • クラスと関数はテスト済みで、Python 2.7および3.4​​で動作します。
  • 内部にすべてのタイプのオブジェクトを含めることができます。これは、それらの表現であり、結果に入れられるそれらのコンテンツではありません(そのため、文字列には引用符があり、Unicode文字列は完全に表現されます...)。
  • クラスバージョンを使用すると、必要なすべてのオブジェクトタイプにフォーマットを追加したり、定義済みのオブジェクトタイプに変更したりできます。
  • キーは任意の有効なタイプにすることができます。
  • インデントと改行の文字は、必要に応じて変更できます。
  • Dict、List、Tuplesはきれいに印刷されています。

2
これは間違いなく受け入れられるソリューションであるはずです-JSONへの依存の欠如は巨大です。
Josh

それがオブジェクト型であることをdictsに変換し、そのキーを設定することにより、オブジェクトを行うことができれば、それはクールになる
アレックス・コーリー

これを行うには、基本的にformat_objectメソッドを内部または外部で置き換えることができます。
y.petremann 2016

set_formater-2つのtが必要です。これはタイプミスであり、フォーマッターである必要があります
Nikolay Prokopyev

32

これにより、たとえば、辞書の名前がyasinであるというきれいな方法で印刷できます。

import json

print (json.dumps(yasin, indent=2))

5
これは、辞書のコンテンツがjsonシリアライズ可能であることを前提としていますが、これは必ずしも正しくありません。
SpiXel

8

別のオプションyapf

from pprint import pformat
from yapf.yapflib.yapf_api import FormatCode

dict_example = {'1': '1', '2': '2', '3': [1, 2, 3, 4, 5], '4': {'1': '1', '2': '2', '3': [1, 2, 3, 4, 5]}}
dict_string = pformat(dict_example)
formatted_code, _ = FormatCode(dict_string)

print(formatted_code)

出力:

{
    '1': '1',
    '2': '2',
    '3': [1, 2, 3, 4, 5],
    '4': {
        '1': '1',
        '2': '2',
        '3': [1, 2, 3, 4, 5]
    }
}

5

他のユーザーが投稿したように、recursion / dfsを使用してネストされた辞書データを出力し、それが辞書の場合は再帰的に呼び出すことができます。それ以外の場合は、データを印刷します。

def print_json(data):
    if type(data) == dict:
            for k, v in data.items():
                    print k
                    print_json(v)
    else:
            print data

5

そのための最もPython的な方法の1つは、すでにビルドされているpprintモジュールを使用することです。

印刷深度を定義するために必要な引数は、予想どおりです depth

import pprint
pp = pprint.PrettyPrinter(depth=4)
pp.pprint(mydict)

それでおしまい !


4

poutは、たとえば、投げたものをきれいに出力できます(data別の回答から借用します)。

data = {'a':2, 'b':{'x':3, 'y':{'t1': 4, 't2':5}}}
pout.vs(data)

次のような出力が画面に出力されます。

{
    'a': 2,
    'b':
    {
        'y':
        {
            't2': 5,
            't1': 4
        },
        'x': 3
    }
}

または、オブジェクトのフォーマットされた文字列出力を返すことができます。

v = pout.s(data)

その主な使用例はデバッグ用であるため、オブジェクトインスタンスやその他のものに影響を与えず、Unicode出力を予想どおりに処理し、Python 2.7および3で動作します。

開示:私はふくれっ面の作者およびメンテナーです。


3

私はsthの答えを取り入れ、ネストされた辞書とリストの私のニーズに合うように少し修正しました:

def pretty(d, indent=0):
    if isinstance(d, dict):
        for key, value in d.iteritems():
            print '\t' * indent + str(key)
            if isinstance(value, dict) or isinstance(value, list):
                pretty(value, indent+1)
            else:
                print '\t' * (indent+1) + str(value)
    elif isinstance(d, list):
        for item in d:
            if isinstance(item, dict) or isinstance(item, list):
                pretty(item, indent+1)
            else:
                print '\t' * (indent+1) + str(item)
    else:
        pass

これにより、次のような出力が得られます。

>>> 
xs:schema
    @xmlns:xs
        http://www.w3.org/2001/XMLSchema
    xs:redefine
        @schemaLocation
            base.xsd
        xs:complexType
            @name
                Extension
            xs:complexContent
                xs:restriction
                    @base
                        Extension
                    xs:sequence
                        xs:element
                            @name
                                Policy
                            @minOccurs
                                1
                            xs:complexType
                                xs:sequence
                                    xs:element
                                            ...

1

Sth、私はそれはかなりシンクします;)

def pretty(d, indent=0):
    for key, value in d.iteritems():
        if isinstance(value, dict):
            print '\t' * indent + (("%30s: {\n") % str(key).upper())
            pretty(value, indent+1)
            print '\t' * indent + ' ' * 32 + ('} # end of %s #\n' % str(key).upper())
        elif isinstance(value, list):
            for val in value:
                print '\t' * indent + (("%30s: [\n") % str(key).upper())
                pretty(val, indent+1)
                print '\t' * indent + ' ' * 32 + ('] # end of %s #\n' % str(key).upper())
        else:
            print '\t' * indent + (("%30s: %s") % (str(key).upper(),str(value)))

1
-1:インスタンスでlistない値dict、つまりpretty({'key': [1, 2, 3]}, indent=4)==>を処理しませんAttributeError: 'int' object has no attribute 'iteritems'。大文字のキーも好きではありません。
martineau 2013年

あなたの解決策は、ルート辞書内のリスト内に辞書はあり得ないと考えています。また、リストやタプルをプリティプリントしたくないと考えています。最後に、キーを大文字にしないでください。{'a':0、 'A':1}の結果は正しくありません。
y.petremann

1
This class prints out a complex nested dictionary with sub dictionaries and sub lists.  
##
## Recursive class to parse and print complex nested dictionary
##

class NestedDictionary(object):
    def __init__(self,value):
        self.value=value

    def print(self,depth):
        spacer="--------------------"
        if type(self.value)==type(dict()):
            for kk, vv in self.value.items():
                if (type(vv)==type(dict())):
                    print(spacer[:depth],kk)
                    vvv=(NestedDictionary(vv))
                    depth=depth+3
                    vvv.print(depth)
                    depth=depth-3
                else:
                    if (type(vv)==type(list())):
                        for i in vv:
                            vvv=(NestedDictionary(i))
                            depth=depth+3
                            vvv.print(depth)
                            depth=depth-3
                    else:
                        print(spacer[:depth],kk,vv) 

##
## Instatiate and execute - this prints complex nested dictionaries
## with sub dictionaries and sub lists
## 'something' is a complex nested dictionary

MyNest=NestedDictionary(weather_com_result)
MyNest.print(0)

1

この単純なコードを記述して、Pythonでjsonオブジェクトの一般的な構造を出力しました。

def getstructure(data, tab = 0):
    if type(data) is dict:
        print ' '*tab + '{' 
        for key in data:
            print ' '*tab + '  ' + key + ':'
            getstructure(data[key], tab+4)
        print ' '*tab + '}'         
    elif type(data) is list and len(data) > 0:
        print ' '*tab + '['
        getstructure(data[0], tab+4)
        print ' '*tab + '  ...'
        print ' '*tab + ']'

次のデータの結果

a = {'list':['a','b',1,2],'dict':{'a':1,2:'b'},'tuple':('a','b',1,2),'function':'p','unicode':u'\xa7',("tuple","key"):"valid"}
getstructure(a)

非常にコンパクトで、次のようになります。

{
  function:
  tuple:
  list:
    [
      ...
    ]
  dict:
    {
      a:
      2:
    }
  unicode:
  ('tuple', 'key'):
}

0

私は自分自身は比較的pythonの初心者ですが、過去数週間、ネストされた辞書を使用してきました。これが私が思いついたものです。

スタックを使用してみてください。ルート辞書のキーをリストのリストにします。

stack = [ root.keys() ]     # Result: [ [root keys] ]

最後から最初に逆の順序で進み、辞書の各キーを検索して、その値が(また)辞書であるかどうかを確認します。そうでない場合は、キーを印刷してから削除します。ただし、キーの値ディクショナリの、キーを出力してから、その値のキーをスタックの最後に追加し、同じ方法でそのリストの処理を開始し、新しいキーのリストごとに再帰的に繰り返します。

各リストの2番目のキーの値がディクショナリである場合、数ラウンド後に次のようなものになります。

[['key 1','key 2'],['key 2.1','key 2.2'],['key 2.2.1','key 2.2.2'],[`etc.`]]

このアプローチの利点は、インデントが\tスタックの長さの数倍になることです。

indent = "\t" * len(stack)

欠点は、各キーをチェックするために、関連するサブディクショナリにハッシュする必要があることですが、これはリスト内包と単純なforループで簡単に処理できます。

path = [li[-1] for li in stack]
# The last key of every list of keys in the stack

sub = root
for p in path:
    sub = sub[p]


if type(sub) == dict:
    stack.append(sub.keys()) # And so on

このアプローチは空のリストを末尾のクリーンアップにあなたを必要とすることに注意してください、(もちろん別の空のリストを作成し、そのようになる場合があります)空のリストが続く任意のリストの最後のキーを削除します。

このアプローチを実装する方法は他にもありますが、うまくいけば、これがそれを行う方法の基本的な考え方を提供してくれるでしょう。

編集:すべてをやりたくない場合、pprintモジュールはネストされた辞書を適切な形式で出力します。


0

これは、sthのコメントに基づいて私が作成した関数です。インデント付きのjson.dumpsと同じように機能しますが、インデント用のスペースの代わりにタブを使用しています。Python 3.2以降では、インデントを直接 '\ t'に指定できますが、2.7ではできません。

def pretty_dict(d):
    def pretty(d, indent):
        for i, (key, value) in enumerate(d.iteritems()):
            if isinstance(value, dict):
                print '{0}"{1}": {{'.format( '\t' * indent, str(key))
                pretty(value, indent+1)
                if i == len(d)-1:
                    print '{0}}}'.format( '\t' * indent)
                else:
                    print '{0}}},'.format( '\t' * indent)
            else:
                if i == len(d)-1:
                    print '{0}"{1}": "{2}"'.format( '\t' * indent, str(key), value)
                else:
                    print '{0}"{1}": "{2}",'.format( '\t' * indent, str(key), value)
    print '{'
    pretty(d,indent=1)
    print '}'

例:

>>> dict_var = {'a':2, 'b':{'x':3, 'y':{'t1': 4, 't2':5}}}
>>> pretty_dict(dict_var)
{
    "a": "2",
    "b": {
        "y": {
            "t2": "5",
            "t1": "4"
        },
        "x": "3"
    }
}

私のソリューションのネストされたdictで機能させることはできません。UnicodeEncodeErrorが与えられたためです。また、アイテムとキーはすべて文字列に変換されます。リストとdictを含む数値またはタプルを使用するとどうなりますか?Finnalyのソリューションでは、きれいに印刷したいオブジェクトは口述である必要があることを考慮に入れています。
y.petremann 2014年

私は、Python dictの一般的な印刷関数を記述しようとしていませんでした。最高評価のコメントは、辞書をきれいに印刷する方法をすでに示しています。私の貢献は、Python 2.7でタブの代わりにインデントするために「\ t」を使用してjson.dumpsの代替を作成することでした。
アルコンラッド

私はjson.dumpsと同じ問題が当てはまるので、json.dumpsの代替を作成することに同意します。また、単純な正規表現を使用してインデントの種類を変更し、コードを簡略化することもできます。
y.petremann 2014年

0

ここでは、途中で「親」辞書を追跡しながら、あらゆる種類のネストされた辞書を印刷します。

dicList = list()

def prettierPrint(dic, dicList):
count = 0
for key, value in dic.iteritems():
    count+=1
    if str(value) == 'OrderedDict()':
        value = None
    if not isinstance(value, dict):
        print str(key) + ": " + str(value)
        print str(key) + ' was found in the following path:',
        print dicList
        print '\n'
    elif isinstance(value, dict):
        dicList.append(key)
        prettierPrint(value, dicList)
    if dicList:
         if count == len(dic):
             dicList.pop()
             count = 0

prettierPrint(dicExample, dicList)

これは、OPで指定されているフォーマットなど、さまざまなフォーマットに従って印刷するための良い出発点です。実際に必要なのは、Printブロックに関する操作だけです。値が「OrderedDict()」であるかどうかを調べることに注意してください。Container datatypes Collectionsから何かを使用しているかどうかに応じて、elifブロックがその名前のために追加のディクショナリとして認識しないように、この種のフェイルセーフを作成する必要があります。今のところ、例のような辞書

example_dict = {'key1': 'value1',
            'key2': 'value2',
            'key3': {'key3a': 'value3a'},
            'key4': {'key4a': {'key4aa': 'value4aa',
                               'key4ab': 'value4ab',
                               'key4ac': 'value4ac'},
                     'key4b': 'value4b'}

印刷します

key3a: value3a
key3a was found in the following path: ['key3']

key2: value2
key2 was found in the following path: []

key1: value1
key1 was found in the following path: []

key4ab: value4ab
key4ab was found in the following path: ['key4', 'key4a']

key4ac: value4ac
key4ac was found in the following path: ['key4', 'key4a']

key4aa: value4aa
key4aa was found in the following path: ['key4', 'key4a']

key4b: value4b
key4b was found in the following path: ['key4']

〜質問の形式に合わせてコードを変更する〜

lastDict = list()
dicList = list()
def prettierPrint(dic, dicList):
    global lastDict
    count = 0
    for key, value in dic.iteritems():
        count+=1
        if str(value) == 'OrderedDict()':
            value = None
        if not isinstance(value, dict):
            if lastDict == dicList:
                sameParents = True
            else:
                sameParents = False

            if dicList and sameParents is not True:
                spacing = ' ' * len(str(dicList))
                print dicList
                print spacing,
                print str(value)

            if dicList and sameParents is True:
                print spacing,
                print str(value)
            lastDict = list(dicList)

        elif isinstance(value, dict):
            dicList.append(key)
            prettierPrint(value, dicList)

        if dicList:
             if count == len(dic):
                 dicList.pop()
                 count = 0

同じサンプルコードを使用して、次のコードを出力します。

['key3']
         value3a
['key4', 'key4a']
                  value4ab
                  value4ac
                  value4aa
['key4']
         value4b

これは、OPで要求されるものとは正確には異なります。違いは、parent ^ nが存在せずに空白で置き換えられるのではなく、まだ印刷されることです。OPのフォーマットを取得するには、次のような何かをする必要があります繰り返し比較dicListをlastDict。あなたはかどうかをチェックする、新しい辞書を作成し、それにdicListのコンテンツをコピーすることによってこれを行うことができ、私がコピーされた辞書に同じである、それがされている場合- -それに空白を書いlastDictで、そしての文字列マルチプライヤ機能を用いた位置。


0

このリンクから:

def prnDict(aDict, br='\n', html=0,
            keyAlign='l',   sortKey=0,
            keyPrefix='',   keySuffix='',
            valuePrefix='', valueSuffix='',
            leftMargin=0,   indent=1 ):
    '''
return a string representive of aDict in the following format:
    {
     key1: value1,
     key2: value2,
     ...
     }

Spaces will be added to the keys to make them have same width.

sortKey: set to 1 if want keys sorted;
keyAlign: either 'l' or 'r', for left, right align, respectively.
keyPrefix, keySuffix, valuePrefix, valueSuffix: The prefix and
   suffix to wrap the keys or values. Good for formatting them
   for html document(for example, keyPrefix='<b>', keySuffix='</b>'). 
   Note: The keys will be padded with spaces to have them
         equally-wide. The pre- and suffix will be added OUTSIDE
         the entire width.
html: if set to 1, all spaces will be replaced with '&nbsp;', and
      the entire output will be wrapped with '<code>' and '</code>'.
br: determine the carriage return. If html, it is suggested to set
    br to '<br>'. If you want the html source code eazy to read,
    set br to '<br>\n'

version: 04b52
author : Runsun Pan
require: odict() # an ordered dict, if you want the keys sorted.
         Dave Benjamin 
         http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/161403
    '''

    if aDict:

        #------------------------------ sort key
        if sortKey:
            dic = aDict.copy()
            keys = dic.keys()
            keys.sort()
            aDict = odict()
            for k in keys:
                aDict[k] = dic[k]

        #------------------- wrap keys with ' ' (quotes) if str
        tmp = ['{']
        ks = [type(x)==str and "'%s'"%x or x for x in aDict.keys()]

        #------------------- wrap values with ' ' (quotes) if str
        vs = [type(x)==str and "'%s'"%x or x for x in aDict.values()] 

        maxKeyLen = max([len(str(x)) for x in ks])

        for i in range(len(ks)):

            #-------------------------- Adjust key width
            k = {1            : str(ks[i]).ljust(maxKeyLen),
                 keyAlign=='r': str(ks[i]).rjust(maxKeyLen) }[1]

            v = vs[i]        
            tmp.append(' '* indent+ '%s%s%s:%s%s%s,' %(
                        keyPrefix, k, keySuffix,
                        valuePrefix,v,valueSuffix))

        tmp[-1] = tmp[-1][:-1] # remove the ',' in the last item
        tmp.append('}')

        if leftMargin:
          tmp = [ ' '*leftMargin + x for x in tmp ]

        if html:
            return '<code>%s</code>' %br.join(tmp).replace(' ','&nbsp;')
        else:
            return br.join(tmp)     
    else:
        return '{}'

'''
Example:

>>> a={'C': 2, 'B': 1, 'E': 4, (3, 5): 0}

>>> print prnDict(a)
{
 'C'   :2,
 'B'   :1,
 'E'   :4,
 (3, 5):0
}

>>> print prnDict(a, sortKey=1)
{
 'B'   :1,
 'C'   :2,
 'E'   :4,
 (3, 5):0
}

>>> print prnDict(a, keyPrefix="<b>", keySuffix="</b>")
{
 <b>'C'   </b>:2,
 <b>'B'   </b>:1,
 <b>'E'   </b>:4,
 <b>(3, 5)</b>:0
}

>>> print prnDict(a, html=1)
<code>{
&nbsp;'C'&nbsp;&nbsp;&nbsp;:2,
&nbsp;'B'&nbsp;&nbsp;&nbsp;:1,
&nbsp;'E'&nbsp;&nbsp;&nbsp;:4,
&nbsp;(3,&nbsp;5):0
}</code>

>>> b={'car': [6, 6, 12], 'about': [15, 9, 6], 'bookKeeper': [9, 9, 15]}

>>> print prnDict(b, sortKey=1)
{
 'about'     :[15, 9, 6],
 'bookKeeper':[9, 9, 15],
 'car'       :[6, 6, 12]
}

>>> print prnDict(b, keyAlign="r")
{
        'car':[6, 6, 12],
      'about':[15, 9, 6],
 'bookKeeper':[9, 9, 15]
}
'''

0

私はsthの回答を取り、小さくて非常に便利な修正を加えた後、この質問に戻っています。この関数は、JSONツリーのすべてのキーとそのツリーのリーフノードサイズを出力します。

def print_JSON_tree(d, indent=0):
    for key, value in d.iteritems():
        print '    ' * indent + unicode(key),
        if isinstance(value, dict):
            print; print_JSON_tree(value, indent+1)
        else:
            print ":", str(type(d[key])).split("'")[1], "-", str(len(unicode(d[key])))

大きなJSONオブジェクトがあり、肉がどこにあるのかを把握したい場合は、非常に便利です。

>>> print_JSON_tree(JSON_object)
key1
    value1 : int - 5
    value2 : str - 16
    key2
       value1 : str - 34
       value2 : list - 5623456

これはJSON_object['key1']['key2']['value2']、文字列としてフォーマットされた値の長さが非常に大きいため、気になるデータのほとんどがおそらく内部にあることを示しています。


0

この関数を使用します。

def pretty_dict(d, n=1):
    for k in d:
        print(" "*n + k)
        try:
            pretty_dict(d[k], n=n+4)
        except TypeError:
            continue

次のように呼び出します。

pretty_dict(mydict)

値が文字列の場合、これは機能しません。文字列の各文字を新しい行に出力しますが、キーは問題なく動作するようです。
アンソニー

0

これは、.txtファイルに辞書を書き込む必要があるクラスで作業しているときに思いついたものです。

@staticmethod
def _pretty_write_dict(dictionary):

    def _nested(obj, level=1):
        indentation_values = "\t" * level
        indentation_braces = "\t" * (level - 1)
        if isinstance(obj, dict):
            return "{\n%(body)s%(indent_braces)s}" % {
                "body": "".join("%(indent_values)s\'%(key)s\': %(value)s,\n" % {
                    "key": str(key),
                    "value": _nested(value, level + 1),
                    "indent_values": indentation_values
                } for key, value in obj.items()),
                "indent_braces": indentation_braces
            }
        if isinstance(obj, list):
            return "[\n%(body)s\n%(indent_braces)s]" % {
                "body": "".join("%(indent_values)s%(value)s,\n" % {
                    "value": _nested(value, level + 1),
                    "indent_values": indentation_values
                } for value in obj),
                "indent_braces": indentation_braces
            }
        else:
            return "\'%(value)s\'" % {"value": str(obj)}

    dict_text = _nested(dictionary)
    return dict_text

今、このような辞書がある場合:

some_dict = {'default': {'ENGINE': [1, 2, 3, {'some_key': {'some_other_key': 'some_value'}}], 'NAME': 'some_db_name', 'PORT': '', 'HOST': 'localhost', 'USER': 'some_user_name', 'PASSWORD': 'some_password', 'OPTIONS': {'init_command': 'SET foreign_key_checks = 0;'}}}

そして私たちはします:

print(_pretty_write_dict(some_dict))

我々が得る:

{
    'default': {
        'ENGINE': [
            '1',
            '2',
            '3',
            {
                'some_key': {
                    'some_other_key': 'some_value',
                },
            },
        ],
        'NAME': 'some_db_name',
        'OPTIONS': {
            'init_command': 'SET foreign_key_checks = 0;',
        },
        'HOST': 'localhost',
        'USER': 'some_user_name',
        'PASSWORD': 'some_password',
        'PORT': '',
    },
}
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.