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!
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.
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.
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.
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 dict
s did not preserve any order until CPython 3.6 (as an implementation detail) and Python 3.7 (as a language guarantee).
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())))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With