可读地打印出按键排序的python dict()

时间:2009-09-25 21:22:12

标签: python

我想使用PrettyPrinter(用于人类可读性)将python字典打印到文件中,但是要在输出文件中按键对字典进行排序,以进一步提高可读性。所以:

mydict = {'a':1, 'b':2, 'c':3}
pprint(mydict)

目前打印到

{'b':2,
 'c':3,
 'a':1}

我想将PrettyPrint打印到字典中,但是打印出按键排序,例如

{'a':1,
 'b':2,
 'c':3}

这样做的最佳方式是什么?

8 个答案:

答案 0 :(得分:84)

实际上pprint似乎是在python2.5

下为你排序的
>>> from pprint import pprint
>>> mydict = {'a':1, 'b':2, 'c':3}
>>> pprint(mydict)
{'a': 1, 'b': 2, 'c': 3}
>>> mydict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
>>> pprint(mydict)
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
>>> d = dict(zip("kjihgfedcba",range(11)))
>>> pprint(d)
{'a': 10,
 'b': 9,
 'c': 8,
 'd': 7,
 'e': 6,
 'f': 5,
 'g': 4,
 'h': 3,
 'i': 2,
 'j': 1,
 'k': 0}

但并不总是在python 2.4下

>>> from pprint import pprint
>>> mydict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
>>> pprint(mydict)
{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4}
>>> d = dict(zip("kjihgfedcba",range(11)))
>>> pprint(d)
{'a': 10,
 'b': 9,
 'c': 8,
 'd': 7,
 'e': 6,
 'f': 5,
 'g': 4,
 'h': 3,
 'i': 2,
 'j': 1,
 'k': 0}
>>> 

阅读pprint.py(2.5)的源代码,它会使用

对字典进行排序
items = object.items()
items.sort()

表示多行,或者这表示单行

for k, v in sorted(object.items()):

在它尝试打印任何内容之前,所以如果你的字典正确排序,那么它应该正确打印。在2.4中,第二个sorted()缺失(当时不存在),因此打印在一行上的对象将不会被排序。

所以答案似乎是使用python2.5,虽然这并不能解释你在问题中的输出。

Python3更新

按排序的(lambda x:x [0])进行漂亮打印:

for key, value in sorted(dict_example.items(), key=lambda x: x[0]): 
    print("{} : {}".format(key, value))

通过排序的(lambda x:x [1])进行漂亮打印:

for key, value in sorted(dict_example.items(), key=lambda x: x[1]): 
    print("{} : {}".format(key, value))

答案 1 :(得分:14)

另一种选择:

>>> mydict = {'a':1, 'b':2, 'c':3}
>>> import json

然后使用python2:

>>> print json.dumps(mydict, indent=4, sort_keys=True) # python 2
{
    "a": 1, 
    "b": 2, 
    "c": 3
}

或使用python 3:

>>> print(json.dumps(mydict, indent=4, sort_keys=True)) # python 3
{
    "a": 1, 
    "b": 2, 
    "c": 3
}

答案 2 :(得分:13)

Python pprint模块实际上已经按键对字典进行排序。在Python 2.5之前的版本中,排序仅在字典上触发,其中漂亮的打印表示跨越多行,但在2.5.X和2.6.X中,所有字典都已排序。

但是,一般情况下,如果您要将数据结构写入文件并希望它们具有人类可读和可写,您可能需要考虑使用YAML或JSON等替代格式。除非您的用户本身就是程序员,否则让他们维护通过pprint转储并通过eval加载的配置或应用程序状态可能是一项令人沮丧且容易出错的任务。

答案 3 :(得分:13)

在Python 3中打印字典的排序内容的简便方法:

>>> dict_example = {'c': 1, 'b': 2, 'a': 3}
>>> for key, value in sorted(dict_example.items()):
...   print("{} : {}".format(key, value))
... 
a : 3
b : 2
c : 1

表达式dict_example.items()返回元组,然后可以按sorted()排序:

>>> dict_example.items()
dict_items([('c', 1), ('b', 2), ('a', 3)])
>>> sorted(dict_example.items())
[('a', 3), ('b', 2), ('c', 1)]

下面是一个例子,用于打印Python字典值的排序内容。

for key, value in sorted(dict_example.items(), key=lambda d_values: d_values[1]): 
    print("{} : {}".format(key, value))

答案 4 :(得分:12)

我编写了以下函数,以更易读的格式打印dicts,lists和tuples:

def printplus(obj):
    """
    Pretty-prints the object passed in.

    """
    # Dict
    if isinstance(obj, dict):
        for k, v in sorted(obj.items()):
            print u'{0}: {1}'.format(k, v)

    # List or tuple            
    elif isinstance(obj, list) or isinstance(obj, tuple):
        for x in obj:
            print x

    # Other
    else:
        print obj

iPython中的用法示例:

>>> dict_example = {'c': 1, 'b': 2, 'a': 3}
>>> printplus(dict_example)
a: 3
b: 2
c: 1

>>> tuple_example = ((1, 2), (3, 4), (5, 6), (7, 8))
>>> printplus(tuple_example)
(1, 2)
(3, 4)
(5, 6)
(7, 8)

答案 5 :(得分:4)

我遇到了同样的问题。我使用了一个for循环,其中sort函数在字典中传递,如下所示:

for item in sorted(mydict):
    print(item)

答案 6 :(得分:3)

您可以稍微改变这个词典,以确保(因为词汇不在内部保存),例如。

pprint([(key, mydict[key]) for key in sorted(mydict.keys())])

答案 7 :(得分:0)

另一个简短的oneliner:

mydict = {'c': 1, 'b': 2, 'a': 3}
print(*sorted(mydict.items()), sep='\n')
相关问题