Python dict的repr(),但已排序
我想要一种简单的方法来获得按键排序的dict的repr-like字符串Python dict的repr(),但已排序,python,dictionary,repr,Python,Dictionary,Repr,我想要一种简单的方法来获得按键排序的dict的repr-like字符串 my_print(dict(a=1, b=2, c=3)) -> "{'a': 1, 'b': 2, 'c': 3}" 我的解决方案: import collections print repr(collections.OrderedDict(sorted(dict(a=1, b=2, c=3).items()))) 。。。不起作用。以下是错误的输出: OrderedDict([('a', 1), ('b', 2)
my_print(dict(a=1, b=2, c=3)) -> "{'a': 1, 'b': 2, 'c': 3}"
我的解决方案:
import collections
print repr(collections.OrderedDict(sorted(dict(a=1, b=2, c=3).items())))
。。。不起作用。以下是错误的输出:
OrderedDict([('a', 1), ('b', 2), ('c', 3)])
如何实现我的打印
这不是一个解决方案,因为DICT在Python中没有排序:
print dict(a=1, b=2, c=3)
那么,您可以使用JSON
import json
import collections
def my_print(x):
return json.dumps(x)
结果:
>>> my_print(collections.OrderedDict(sorted(dict(a=1, b=2, c=3).items())))
'{"a": 1, "b": 2, "c": 3}'
那么,您可以使用JSON
import json
import collections
def my_print(x):
return json.dumps(x)
结果:
>>> my_print(collections.OrderedDict(sorted(dict(a=1, b=2, c=3).items())))
'{"a": 1, "b": 2, "c": 3}'
JSON只适用于简单类型。可以这样手动完成:
print '{' + ', '.join('%r: %r' % i for i in od.iteritems()) + '}'
其中od是collections.OrderedDict对象。JSON仅适用于简单类型。可以这样手动完成:
print '{' + ', '.join('%r: %r' % i for i in od.iteritems()) + '}'
其中od是collections.OrderedDict对象。Python 3.7中的标准字典是,而CPython 3.6中的dict是,因此以下内容将适用于Python 3.7,也可能适用于Python 3.6:
def sorted_dict_repr(d):
return repr(dict(sorted(d.items())))
Python 3.7中的标准字典是,而在CPython 3.6中,dict是,因此以下内容将适用于Python 3.7,可能也适用于您的Python 3.6:
def sorted_dict_repr(d):
return repr(dict(sorted(d.items())))
这个输出到底出了什么问题?@deceze应该对输出进行排序。报告。。没有排序。因为dict没有排序。你的错误输出样本在我看来非常排序…@deceze:有两个要求:1。排序2。就像一本字典。OrderedDict已排序,但不像字典。字典就像字典,但没有排序。这个输出到底出了什么问题?@deceze应该对输出进行排序。报告。。没有排序。因为dict没有排序。你的错误输出样本在我看来非常排序…@deceze:有两个要求:1。排序2。就像一本字典。OrderedDict已排序,但不像字典。字典就像字典,但没有排序。那么为什么json.dumpsdicta=1,b=2,c=3,sort\u keys=True不呢?这样嵌套的字典也将按键排序……那么为什么不使用json.dumpsdicta=1、b=2、c=3、sort\u keys=True呢?这样嵌套字典也将按键排序。。。