2

我想要一种简单的方法来获取 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)
4

3 回答 3

3

Python 3.7 中的标准字典将被排序,而在 CPython 3.6 中,由于实现细节而dict被排序,因此以下内容将适用于 Python 3.7,并且可能也适用于您的 Python 3.6:

def sorted_dict_repr(d):
    return repr(dict(sorted(d.items())))
于 2018-02-25T19:13:53.280 回答
2

好吧,您可以使用 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}'
于 2016-04-12T11:17:20.707 回答
1

JSON 仅适用于简单类型。手动可以这样做:

print '{' + ', '.join('%r: %r' % i for i in od.iteritems()) + '}'

od对象在哪里collections.OrderedDict

于 2016-04-12T12:14:55.430 回答