在字典中根据相同值查找所有关键元素

11 投票
4 回答
31271 浏览
提问于 2025-04-16 11:14

我有一个关于Python中字典的问题。

问题是这样的:

我有一个字典,比如 dict = { 'abc':'a', 'cdf':'b', 'gh':'a', 'fh':'g', 'hfz':'g' }

现在我想根据相同的值获取所有的键,并把它们保存到一个新的字典里。

新的字典应该看起来像这样:

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

4 个回答

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)

这样得到的结果和上面是一样的。

6

这里有一个简单的实现方法。懂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']}
22

如果你可以接受在新的字典里用列表代替元组,你可以使用

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)

撰写回答