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


81

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

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

当前打印到

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

我想使用PrettyPrint字典,但要按键将其打印出来。

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

做这个的最好方式是什么?

python 

原来pprint已经按键排序了。应该更仔细地检查一下。

Answers:


94

其实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))

Python 3 lambda表达式解决方案很漂亮。为了清楚起见,我相信(?)keyinfor key, value in ...keyin无关,key=lambda ...因为它起作用,for k,v in sorted(token_dict.items(), key=lambda x: x[0])但是for k,v in sorted(token_dict.items(), k=lambda x: x[0])会引发错误。
维多利亚·斯图尔特

18

另一种选择:

>>> 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
}

14

在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))

非常好。这是一个漂亮地打印Python字典值的排序内容的示例:for key, value in sorted(dict_example.items(), key=lambda d_items: d_items[1]): print("{} : {}".format(key, value))
Scott Skiles

1
@ScottSkiles,您应编辑答案并在其中添加示例-我认为这将对将来的读者有所帮助
redbeam_

13

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

但是,通常,如果您正在将数据结构写到文件中并希望它们可被人类读取和写入,则可能需要考虑使用另一种格式,例如YAML或JSON。除非您的用户本身是程序员,否则让他们维护通过转储pprint和通过转储加载的配置或应用程序状态eval可能是一件令人沮丧且容易出错的任务。


2
顺便说一句,ast.literal_eval("{'a': 0, 'b': 1, 2: 'c'}")->{2: 'c', 'a': 0, 'b': 1}所以不需要冒充eval
jfs

是的,显然pprint无法提供关闭此行为的方法。浪费了一两个小时,试图弄清楚为什么某些pprint样本报告数据被按键排序。
萨曼莎·阿特金斯

12

我编写了以下函数,以更易读的格式打印字典,列表和元组:

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

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

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

4

您可以对此字典进行一些转换以确保(因为字典未在内部进行排序),例如

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

0

另一个简短的oneliner:

mydict = {'c': 1, 'b': 2, 'a': 3}
print(*sorted(mydict.items()), sep='\n')
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.