将 Python 字典键分组为一个列表,并使用此列表作为值创建一个新字典
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15751979/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Grouping Python dictionary keys as a list and create a new dictionary with this list as a value
提问by Shankar
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 vshould 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.
注意新字典v的键应该被排序。我发现很难想象和实现这个字典的创建。请建议我一个简单有效的方法来做到这一点。
采纳答案by Martijn Pieters
Using collections.defaultdictfor ease:
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 dicttoo, using dict.setdefault():
但是你也可以使用沼泽标准来做到这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 notneed 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).
(集合值的输出被排序是一个巧合,整数哈希值的实现方式的副作用;集合是无序结构)。
回答by mgilson
If you don't actually need a dictat the end of the day, you could use itertools.groupby:
如果您dict在一天结束时实际上不需要 a ,则可以使用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 解决方案。

