我想使用PrettyPrinter将python字典打印到一个文件中(为了便于阅读),但为了进一步提高可读性,我在输出文件中按键对字典进行了排序。所以:
mydict = {'a':1, 'b':2, 'c':3}
pprint(mydict)
当前打印到
{'b':2,
'c':3,
'a':1}
我想把字典打印出来,但要按关键字PrettyPrint。
{'a':1,
'b':2,
'c':3}
做这件事最好的方法是什么?
发布于 2016-03-31 22:32:36
另一种替代方案:
>>> 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
}
发布于 2013-08-14 05:07:44
在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))
发布于 2012-08-03 11:51:19
我编写了以下函数,以便以更易读的格式打印字典、列表和元组:
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)
https://stackoverflow.com/questions/1479649
复制相似问题