在Dicts中查找具有相同值的所有关键元素 [英] Find all Key-Elements by the same Value in Dicts

查看:63
本文介绍了在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)

这篇关于在Dicts中查找具有相同值的所有关键元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆