76 python
我想使用PrettyPrinter(用于人类可读性)将python字典打印到文件中,但是要在输出文件中按键对字典进行排序,以进一步提高可读性.所以:
mydict = {'a':1, 'b':2, 'c':3}
pprint(mydict)
Run Code Online (Sandbox Code Playgroud)
目前打印到
{'b':2,
'c':3,
'a':1}
Run Code Online (Sandbox Code Playgroud)
我想将PrettyPrint字典打印出来,但是按照键排序打印出来,例如.
{'a':1,
'b':2,
'c':3}
Run Code Online (Sandbox Code Playgroud)
做这个的最好方式是什么?
Nic*_*ood 87
实际上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}
Run Code Online (Sandbox Code Playgroud)
但并不总是在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}
>>>
Run Code Online (Sandbox Code Playgroud)
阅读pprint.py(2.5)的源代码,它会对字典进行排序
items = object.items()
items.sort()
Run Code Online (Sandbox Code Playgroud)
对于多行或对于单行
for k, v in sorted(object.items()):
Run Code Online (Sandbox Code Playgroud)
在它尝试打印任何东西之前,所以如果你的字典正确排序,那么它应该正确打印.在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))
Run Code Online (Sandbox Code Playgroud)
按排序值进行漂亮打印(lambda x:x [1]):
for key, value in sorted(dict_example.items(), key=lambda x: x[1]):
print("{} : {}".format(key, value))
Run Code Online (Sandbox Code Playgroud)
Ski*_*rou 15
另一种选择:
>>> mydict = {'a':1, 'b':2, 'c':3}
>>> import json
Run Code Online (Sandbox Code Playgroud)
然后使用python2:
>>> print json.dumps(mydict, indent=4, sort_keys=True) # python 2
{
"a": 1,
"b": 2,
"c": 3
}
Run Code Online (Sandbox Code Playgroud)
或者使用python 3:
>>> print(json.dumps(mydict, indent=4, sort_keys=True)) # python 3
{
"a": 1,
"b": 2,
"c": 3
}
Run Code Online (Sandbox Code Playgroud)
Zwe*_*end 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
Run Code Online (Sandbox Code Playgroud)
表达式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)]
Run Code Online (Sandbox Code Playgroud)
下面是一个相当打印Python字典值的排序内容的示例.
for key, value in sorted(dict_example.items(), key=lambda d_values: d_values[1]):
print("{} : {}".format(key, value))
Run Code Online (Sandbox Code Playgroud)
rco*_*der 13
Python pprint模块实际上已经按键对字典进行排序.在Python 2.5之前的版本中,排序仅在字典上触发,其中漂亮的打印表示跨越多行,但在2.5.X和2.6.X中,所有字典都被排序.
但是,一般情况下,如果您将数据结构写入文件并希望它们具有人类可读和可写,您可能需要考虑使用YAML或JSON等替代格式.除非您的用户本身就是程序员,否则让他们维护配置或应用程序状态通过转储pprint和加载通过eval可能是一个令人沮丧且容易出错的任务.
Sco*_*ter 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
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
小智 5
我遇到了和你一样的问题。我使用了一个带有排序函数的 for 循环在字典中传递,如下所示:
for item in sorted(mydict):
print(item)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
138381 次 |
| 最近记录: |