简体   繁体   中英

repr() of dict, but ordered

I want a simple way to get the repr() like string of a dict sorted by the keys.

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() ?

This is not a solution since dicts are not sorted in Python:

print dict(a=1, b=2, c=3)

Well, you can use 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. Manually it could be done like that:

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

where od is collections.OrderedDict object.

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:

def sorted_dict_repr(d):
    return repr(dict(sorted(d.items())))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM