我想要一种简单的方法来获取 repr() 之类的按键排序的字典字符串。
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)])
如何实施my_print()
?
这不是一个解决方案,因为 dicts 在 Python 中没有排序:
print dict(a=1, b=2, c=3)