How to reverse dictionary items and list keys grouped by common values [duplicate]

拟墨画扇 提交于 2021-02-16 18:21:48

问题


I have a dictionary that I want to group by the common values:

init_dict = {'00001': 'string1', '00002': 'string2', '00003': 'string1', '00004': 'string3', '00005': 'string2'}

I want to create a new dictionary that groups the values and lists the keys like this:

new_dict = {'string1': ['00001', '00003'], 'string2':['00002', '00004'], 'string3': ['00004']}

I tried many things and this is the closest I can get.

lookup = 'string1'
all_keys = []
for k, v in init_dict.items():
  if v == lookup:
    all_keys.append(k)
print(all_keys)

This produces the first list: ['00001', '00003'] so I thought I could somehow loop through a list of lookup values but can't since I'm working with strings. Is there a way to do this and is there a way that is relatively efficient because my initial dictionary has 53,000 items in it. Any help would be much appreciated as I've been trying different things for hours.


回答1:


Use a defaultdict, specifying a list as default argument, and append the corresponding values from the dictionary:

from collections import defaultdict

d =  defaultdict(list)
for k,v in init_dict.items():
    d[v].append(k)

print(d)

defaultdict(list,
            {'string1': ['00001', '00003'],
             'string2': ['00002', '00005'],
             'string3': ['00004']})



回答2:


You can use defaultdict

result = defaultdict(list)
for k, v in init_dict.items():
    result[v].append(k)

or itertools.groupby

result = {k: [x[0] for x in v] for k, v in
          groupby(sorted(init_dict.items(), key=lambda kv: kv[1]), key=lambda kv: kv[1])}



回答3:


You can also use a normal dict (instead of defaultdict):

new_dict = {}
for key, val in init_dict.items():
    if val in new_dict:
        new_dict[val].append(key)
    else:
        new_dict[val] = []
        new_dict[val].append(key)

Output:

new_dict = {'string1': ['00001', '00003'],
            'string2': ['00002', '00005'], 
            'string3': ['00004']}


来源:https://stackoverflow.com/questions/61427141/how-to-reverse-dictionary-items-and-list-keys-grouped-by-common-values

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