5

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.

martineau
  • 119,623
  • 25
  • 170
  • 301
Amit Singh
  • 135
  • 1
  • 1
  • 8

4 Answers4

6

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]}
Chiheb Nexus
  • 9,104
  • 4
  • 30
  • 43
  • 1
    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? – user3240688 May 13 '22 at 15:15
5

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]})
Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485
1
o = {}
for k,v in d.iteritems():
    if v in o:
        o[v].append(k)
    else:
        o[v] = [k]

o = {10: [1], 20: [2], 30: [3, 4]}

Andrew
  • 1,890
  • 3
  • 16
  • 35
  • 1
    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. – Donald Duck Jun 30 '17 at 22:56
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!

Dishant Kapadiya
  • 523
  • 4
  • 10