Python reverse dictionary items order

混江龙づ霸主 提交于 2021-01-13 08:00:34

问题


Assume I have a dictionary:

d = {3: 'three', 2: 'two', 1: 'one'}

I want to rearrange the order of this dictionary so that the dictionary is:

d = {1: 'one', 2: 'two', 3: 'three'}

I was thinking something like the reverse() function for lists, but that did not work. Thanks in advance for your answers!


回答1:


Since Python 3.8 and above, the items view is iterable in reverse, so you can just do:

d = dict(reversed(d.items()))

On 3.7 and 3.6, they hadn't gotten around to implementing __reversed__ on dict and dict views (issue33462: reversible dict), so use an intermediate list or tuple, which do support reversed iteration:

d = {3: 'three', 2: 'two', 1: 'one'}
d = dict(reversed(list(d.items())))

Pre-3.6, you'd need collections.OrderedDict (both for the input and the output) to achieve the desired result. Plain dicts did not preserve any order until CPython 3.6 (as an implementation detail) and Python 3.7 (as a language guarantee).




回答2:


Standard Python dictionaries (Before Python 3.6) don't have an order and don't guarantee order. This is exactly what the creation of OrderedDict is for.

If your Dictionary was an OrderedDict you could reverse it via:

import collections

mydict = collections.OrderedDict()
mydict['1'] = 'one'
mydict['2'] = 'two'
mydict['3'] = 'three'

collections.OrderedDict(reversed(list(mydict.items())))



回答3:


Another straightforward solution, which is guaranteed to work for Python v3.7 and over:

d = {'A':'a', 'B':'b', 'C':'c', 'D':'d'}
dr = {k: d[k] for k in reversed(d)}

print(dr)

Output:

{'D': 'd', 'C': 'c', 'B': 'b', 'A': 'a'}

Note that reversed dictionaries are still considered equal to their unreversed originals, i.e.:

(d == dr) == True


来源:https://stackoverflow.com/questions/55911745/python-reverse-dictionary-items-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!