将 Python 字典键分组为一个列表,并使用此列表作为值创建一个新字典 [英] Grouping Python dictionary keys as a list and create a new dictionary with this list as a value

查看:38
本文介绍了将 Python 字典键分组为一个列表,并使用此列表作为值创建一个新字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一本python字典

I have a python dictionary

d = {1: 6, 2: 1, 3: 1, 4: 9, 5: 9, 6: 1}

由于上述字典中的值不是唯一的.我想将唯一值的所有键分组为一个列表并创建一个新字典,如下所示:

Since the values in the above dictionary are not unique. I want to group the all the keys of unique values as a list and create a new dictionary as follows:

v = {6:[1], 1:[2, 3, 6], 9: [4, 5]}

注意新字典v的键应该是排序的.我发现很难想象和实现这个字典的创建.请给我建议一个简单有效的方法.

Note the keys of new dictionary v should be sorted. I am finding it hard to visualize and implement this dictionary creation. Please suggest me an easy and efficient way to do it.

推荐答案

使用 <代码>collections.defaultdict 为方便:

Using collections.defaultdict for ease:

from collections import defaultdict

v = defaultdict(list)

for key, value in sorted(d.items()):
    v[value].append(key)

但是你也可以使用 bog-standard dict 来实现,使用 dict.setdefault():

but you can do it with a bog-standard dict too, using dict.setdefault():

v = {}

for key, value in sorted(d.items()):
    v.setdefault(value, []).append(key)

以上对key进行排序first;稍后对输出字典的值进行排序会更加麻烦和低效.

The above sorts keys first; sorting the values of the output dictionary later is much more cumbersome and inefficient.

如果有人不需要需要对输出进行排序,您可以删除 sorted() 调用,并使用 sets(键在输入字典中保证是唯一的,所以不会丢失任何信息):

If anyone would not need the output to be sorted, you can drop the sorted() call, and use sets (the keys in the input dictionary are guaranteed to be unique, so no information is lost):

v = {}

for key, value in d.items():
    v.setdefault(value, set()).add(key)

生产:

{6: {1}, 1: {2, 3, 6}, 9: {4, 5}}

(集合值的输出被排序是巧合,是整数哈希值实现方式的副作用;集合是无序结构).

(that the output of the set values is sorted is a coincidence, a side-effect of how hash values for integers are implemented; sets are unordered structures).

这篇关于将 Python 字典键分组为一个列表,并使用此列表作为值创建一个新字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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