简体   繁体   English

将 Python 字典键分组为一个列表,并使用此列表作为值创建一个新字典

[英]Grouping Python dictionary keys as a list and create a new dictionary with this list as a value

I have a python dictionary我有一个 python 字典

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

Note the keys of new dictionary v should be sorted.注意新字典v的键应该被排序。 I am finding it hard to visualize and implement this dictionary creation.我发现很难想象和实现这个字典的创建。 Please suggest me an easy and efficient way to do it.请建议我一个简单有效的方法来做到这一点。

Using collections.defaultdict for ease:使用collections.defaultdict轻松:

from collections import defaultdict

v = defaultdict(list)

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

but you can do it with a bog-standard dict too, using dict.setdefault() :但是你也可以使用 bog-standard dict来做到这一点,使用dict.setdefault()

v = {}

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

The above sorts keys first ;上面首先对键进行排序; sorting the values of the output dictionary later is much more cumbersome and inefficient.稍后对输出字典的值进行排序会更加麻烦和低效。

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):如果有人不需要输出进行排序,你可以删除sorted()调用,使用了一(在输入字典键被保证是唯一的,所以没有信息丢失):

v = {}

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

to produce:生产:

{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). (集合值的输出被排序是一个巧合,整数哈希值的实现方式的副作用;集合是无序结构)。

If you don't actually need a dict at the end of the day, you could use itertools.groupby :如果您在一天结束时实际上不需要dict ,则可以使用itertools.groupby

from itertools import groupby
from operator import itemgetter

for k, v in groupby(sorted(d.items(), key=itemgetter(1)), itemgetter(1)):
    print(k, list(map(itemgetter(0), v)))

Of course, you could use this to construct a dict if you really wanted to:当然,如果你真的想,你可以用它来构造一个 dict:

{
    k: list(map(itemgetter(0), v))
    for k, v in groupby(sorted(d.items(), key=itemgetter(1)), itemgetter(1))
}

But at that point, you're probably better off using Martijn's defaultdict solution.但此时,您最好使用 Martijn 的 defaultdict 解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM