我想使用PrettyPrinter将python字典打印到一个文件中(以提高可读性),但是要使字典按输出文件中的键排序,以进一步提高可读性。所以:
mydict = {'a':1, 'b':2, 'c':3}
pprint(mydict)
当前打印到
{'b':2,
'c':3,
'a':1}
我想使用PrettyPrint字典,但要按键将其打印出来。
{'a':1,
'b':2,
'c':3}
做这个的最好方式是什么?
我想使用PrettyPrinter将python字典打印到一个文件中(以提高可读性),但是要使字典按输出文件中的键排序,以进一步提高可读性。所以:
mydict = {'a':1, 'b':2, 'c':3}
pprint(mydict)
当前打印到
{'b':2,
'c':3,
'a':1}
我想使用PrettyPrint字典,但要按键将其打印出来。
{'a':1,
'b':2,
'c':3}
做这个的最好方式是什么?
Answers:
其实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))
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])会引发错误。
另一种选择:
>>> 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
}
在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))
for key, value in sorted(dict_example.items(), key=lambda d_items: d_items[1]): print("{} : {}".format(key, value))
Pythonpprint模块实际上已经按键对字典进行排序。在Python 2.5之前的版本中,仅在字典的漂亮打印内容跨越多行时才触发排序,但是在2.5.X和2.6.X中,所有字典都被排序。
但是,通常,如果您正在将数据结构写到文件中并希望它们可被人类读取和写入,则可能需要考虑使用另一种格式,例如YAML或JSON。除非您的用户本身是程序员,否则让他们维护通过转储pprint和通过转储加载的配置或应用程序状态eval可能是一件令人沮丧且容易出错的任务。
ast.literal_eval("{'a': 0, 'b': 1, 2: 'c'}")->{2: 'c', 'a': 0, 'b': 1}所以不需要冒充eval。
我编写了以下函数,以更易读的格式打印字典,列表和元组:
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)