在Dicts中按相同的值查找所有关键元素

时间:2011-02-04 16:23:27

标签: python dictionary key

我对Python中的字典有疑问。

这里是:

我有一个像dict = { 'abc':'a', 'cdf':'b', 'gh':'a', 'fh':'g', 'hfz':'g' }

这样的字典

现在我希望以相同的值获取所有Key-Elements并将其保存在新的dict中。

新的Dict应该是这样的:

new_dict = { 'b':('cdf'), 'a':('abc','gh'), 'g':('fh','hfz')}

4 个答案:

答案 0 :(得分:21)

如果您在新词典中使用列表而不是元组,则可以使用

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,您也可以

new_dict = {}
for k, v in some_dict.iteritems():
    new_dict.setdefault(v, []).append(k)

答案 1 :(得分:2)

这是一个天真的实现。拥有更好Python技能的人可能会使它更简洁和更棒。

dict = { 'abc':'a', 'cdf':'b', 'gh':'a', 'fh':'g', 'hfz':'g' }

new_dict = {}
for pair in dict.items():
    if pair[1] not in new_dict.keys():
        new_dict[pair[1]] = []

    new_dict[pair[1]].append(pair[0])

print new_dict

这会产生

{'a': ['abc', 'gh'], 'b': ['cdf'], 'g': ['fh', 'hfz']}

答案 2 :(得分:0)

如果您确实希望元组作为新字典中的值,您仍然可以使用defaultdict,并使用元组连接。此解决方案适用于Python 3.4 +:

from collections import defaultdict

source = {'abc': 'a', 'cdf': 'b', 'gh': 'a', 'fh': 'g', 'hfz': 'g'}
target = defaultdict(tuple)

for key in source:
    target[source[key]] += (key, )

print(target)

哪个会产生

defaultdict(<class 'tuple'>, {'a': ('abc', 'gh'), 'g': ('fh', 'hfz'), 'b': ('cdf',)})

这可能比通过列表插入生成字典慢,并且将创建更多要收集的对象。因此,您可以从列表中构建字典,然后将其映射到元组:

target2 = defaultdict(list)

for key in source:
    target2[source[key]].append(key)

for key in target2:
    target2[key] = tuple(target2[key])

print(target2)

这将得到与上述相同的结果。

答案 3 :(得分:0)

也可以通过这种方式完成,而无需使用任何其他功能。

some_dict = { 'abc':'a', 'cdf':'b', 'gh':'a', 'fh':'g', 'hfz':'g' }
new_dict = { }
for keys in some_dict:
    new_dict[some_dict[keys]] = [ ]
for keys in some_dict:
    new_dict[some_dict[keys]].append(keys)
    
print(new_dict)