How do I reverse the order of key-value pairs of a dictionary, in Python? For example, I have this dictionary:
{"a":1, "b":2, "c":3}
I want to reverse it so that it returns:
{"c":3, "b":2, "a":1}
Is there a function that I haven't heard about that can do this? Some lines of code is fine as well.
1) Using OrderedDict() and items() method Later you make use of a reversed() function which is an in-built python method that takes an argument as the sequence data types like tuple, lists, dictionaries, etc and returns the reverse of it.
Duplicate keys are not allowed. A dictionary maps each key to a corresponding value, so it doesn't make sense to map a particular key more than once.
Use items() to Reverse a Dictionary in Python Reverse the key-value pairs by looping the result of items() and switching the key and the value. The k and v in the for loop stands for key and value respectively.
The straight answer is NO. You can not have duplicate keys in a dictionary in Python.
Dictionary does not have any sense of order , so your key/value pairs are not ordered in any format.
If you want to preserve the order of the keys, you should use collections.OrderedDict
from the start, instead of using normal dictionary , Example -
>>> from collections import OrderedDict
>>> d = OrderedDict([('a',1),('b',2),('c',3)])
>>> d
OrderedDict([('a', 1), ('b', 2), ('c', 3)])
OrderedDict would preserve the order in which the keys were entered into the dictionary. In above case, it would be the order in which the keys existed in the list - [('a',1),('b',2),('c',3)]
- 'a' -> 'b' -> 'c'
Then you can get the reversed order of keys using reversed(d)
, Example -
>>> dreversed = OrderedDict()
>>> for k in reversed(d):
... dreversed[k] = d[k]
...
>>> dreversed
OrderedDict([('c', 3), ('b', 2), ('a', 1)])
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