如何反转按公用值分组的字典项和列表键 [英] How to reverse dictionary items and list keys grouped by common values

查看:38
本文介绍了如何反转按公用值分组的字典项和列表键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字典,希望按常用值进行分组:

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)

这将产生第一个列表: ['00001','00003'] ,所以我想我可以以某种方式遍历 lookup 值列表,但是由于我正在使用琴弦.有没有办法做到这一点,有没有一种比较有效的办法,因为我的初始词典中有53,000项.感谢所有帮助,因为我已经尝试了数小时的尝试.

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.

推荐答案

使用

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

这篇关于如何反转按公用值分组的字典项和列表键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆