在Dicts中查找具有相同值的所有关键元素
问题描述:
我对Python中的字典有疑问.
I have question about Dictionaries in Python.
在这里:
我有一个像dict = { 'abc':'a', 'cdf':'b', 'gh':'a', 'fh':'g', 'hfz':'g' }
现在,我想通过相同的值获取所有关键元素并将其保存在新的字典中.
Now i want to get all Key-Elements by the same value and save it in a new dict.
新的字典应如下所示:
new_dict = { 'b':('cdf'), 'a':('abc','gh'), 'g':('fh','hfz')}
答
如果您对新字典中的列表(而不是元组)比较满意,则可以使用
If you are fine with lists instead of tuples in the new dictionary, you can use
from collections import defaultdict
some_dict = { 'abc':'a', 'cdf':'b', 'gh':'a', 'fh':'g', 'hfz':'g' }
new_dict = defaultdict(list)
for k, v in some_dict.iteritems():
new_dict[v].append(k)
如果您想避免使用defaultdict
,也可以这样做
If you want to avoid the use of defaultdict
, you could also do
new_dict = {}
for k, v in some_dict.iteritems():
new_dict.setdefault(v, []).append(k)