Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse a dictionary in python to key : list of values?

How to convert a python dictionary d = {1:10, 2:20, 3:30, 4:30} to {10: [1], 20: [2], 30: [3, 4]}?

I need to reverse a dictionary the values should become the keys of another dictionary and the values should be key in a list i.e. also in the sorted matter.

like image 288
Amit Singh Avatar asked Jun 30 '17 16:06

Amit Singh


People also ask

How do you reverse the keys and 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 reverse a dictionary key 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. Remember that reversed() method does not modify the original iterator.

How do I get a list of key values in a dictionary?

keys() function to make your code more explicit. To get a list of the dictionary's values, you can call the dict. values() function.


2 Answers

Reversing keys and values in a python dict is a bit tricky. You should have in mind that a python dict must have a unique keys.

So, if you know that when reversing keys and values of your current dict will have a unique keys, you can use a simple dict comprehension like this example:

{v:k  for k,v in my_dict.items()}

However, you can use groupby from itertools module like this example:

from itertools import groupby

a = {1:10, 2:20, 3:30, 4:30}
b = {k: [j for j, _ in list(v)] for k, v in groupby(a.items(), lambda x: x[1])}
print(b)

>>> {10: [1], 20: [2], 30: [3, 4]}
like image 166
Chiheb Nexus Avatar answered Oct 21 '22 10:10

Chiheb Nexus


This use case is easily handled by dict.setdefault()

>>> d = {1:10, 2:20, 3:30, 4:30}
>>> e = {}
>>> for x, y in d.items():
        e.setdefault(y, []).append(x)

>>> e
{10: [1], 20: [2], 30: [3, 4]}

An alternative is to use collections.defaultdict. This has a slightly more complex set-up, but the inner-loop access is simpler and faster than the setdefault approach. Also, it returns a dict subclass rather than a plain dict:

>>> e = defaultdict(list)
>>> for x, y in d.items():
        e[y].append(x)

>>> e
defaultdict(<class 'list'>, {30: [3, 4], 10: [1], 20: [2]})
like image 25
Raymond Hettinger Avatar answered Oct 21 '22 11:10

Raymond Hettinger