[英]repr() of dict, but ordered
I want a simple way to get the repr() like string of a dict sorted by the keys. 我想要一种简单的方法来获得repr()像按键排序的字典字符串。
my_print(dict(a=1, b=2, c=3)) -> "{'a': 1, 'b': 2, 'c': 3}"
My solution: 我的解决方案:
import collections
print repr(collections.OrderedDict(sorted(dict(a=1, b=2, c=3).items())))
... does not work. ...不起作用。 Here the wrong output:
这里输出错误:
OrderedDict([('a', 1), ('b', 2), ('c', 3)])
How to implement my_print()
? 如何实现
my_print()
?
This is not a solution since dicts are not sorted in Python: 这不是解决方案,因为字典未在Python中排序:
print dict(a=1, b=2, c=3)
Well, you can use JSON. 好了,您可以使用JSON。
import json
import collections
def my_print(x):
return json.dumps(x)
Result: 结果:
>>> my_print(collections.OrderedDict(sorted(dict(a=1, b=2, c=3).items())))
'{"a": 1, "b": 2, "c": 3}'
JSON will work only for simple types. JSON仅适用于简单类型。 Manually it could be done like that:
可以手动执行以下操作:
print '{' + ', '.join('%r: %r' % i for i in od.iteritems()) + '}'
where od
is collections.OrderedDict
object. 其中
od
是collections.OrderedDict
对象。
The standard dictionary in Python 3.7 is going to be ordered , and in CPython 3.6, dict
is ordered due to an implementation detail , so the following will work with Python 3.7, and probably with your Python 3.6 too: Python 3.7中的标准字典将被排序 ,而CPython 3.6中的
dict
由于实现细节而被排序 ,因此以下内容将在Python 3.7以及您的Python 3.6中运行:
def sorted_dict_repr(d):
return repr(dict(sorted(d.items())))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.