Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reversing the order of key-value pairs in a dictionary (Python) [duplicate]

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.

like image 374
finego Avatar asked Aug 20 '15 05:08

finego


People also ask

How do you reverse the order of a dictionary in Python?

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.

Can a dictionary have duplicate key value pairs?

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.

How do you reverse a key value pair in Python?

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.

Can we duplicate keys in Python dictionary?

The straight answer is NO. You can not have duplicate keys in a dictionary in Python.


1 Answers

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)])
like image 102
Anand S Kumar Avatar answered Sep 24 '22 17:09

Anand S Kumar