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

痴心易碎 提交于 2020-06-16 16:43:02

问题


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.


回答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!




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



回答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]})



回答4:


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




回答5:


This SO question explains how to do this in Python 2.7.x and 3+:

Python reverse / invert a mapping

In an answer below it is shown that this method:

inv_map = {}
for k, v in d.iteritems():
    inv_map[v] = inv_map.get(v, [])
    inv_map[v].append(k)

Is best.



来源:https://stackoverflow.com/questions/44851342/reverse-a-dictionary-in-python-to-key-list-of-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!