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

10,701

Solution 1

d = {1:10, 2:20, 3:30, 4:30}
inv = {}
for key, val in d.iteritems():
    inv[val] = inv.get(val, []) + [key]

Try this!

Solution 2

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]}

Solution 3

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]})
Share:
10,701
Amit Singh
Author by

Amit Singh

Updated on June 04, 2022

Comments

  • Amit Singh
    Amit Singh almost 2 years

    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.

  • Donald Duck
    Donald Duck almost 7 years
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.
  • user3240688
    user3240688 almost 2 years
    I don't see how the groupby way would work if the input is not sorted. So for example, if we switch the ordering of a from {1:10, 2:20, 3:30, 4:30} to {1:10, 3:30, 2:20, 4:30}, wouldn't group by fail?