Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python reverse dictionary items order

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!

like image 259
SomeMosa Avatar asked Apr 29 '19 22:04

SomeMosa


People also ask

How do you reverse key values in a dictionary?

Use items() to Reverse a Dictionary in Python Printing a dictionary using items() will output an iterable list of tuple values that we can manipulate using the for loop for dictionaries. Reverse the key-value pairs by looping the result of items() and switching the key and the value.

How do you sort a dictionary by value in Python descending?

Sorting a dict by value descending using list comprehension. The quickest way is to iterate over the key-value pairs of your current dict and call sorted passing the dictionary values and setting reversed=True . If you are using Python 3.7, regular dict s are ordered by default.

Can we reverse a dictionary?

Instead of using a for loop, we can reverse a dictionary in a single python statement using dictionary comprehension. Here, we will create the output dictionary by reversing the key and value in each key-value pair of the dictionary as follows.


2 Answers

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).

like image 141
ShadowRanger Avatar answered Oct 21 '22 04:10

ShadowRanger


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())))
like image 2
Bradd Avatar answered Oct 21 '22 02:10

Bradd