Python 在字典中按相同的值查找所有关键元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4900308/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 18:01:43  来源:igfitidea点击:

Find all Key-Elements by the same Value in Dicts

pythondictionarykey

提问by Sv3n

I have question about Dictionaries in Python.

我对 Python 中的字典有疑问。

here it is:

这里是:

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

我有一个像 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.

现在我想通过相同的值获取所有关键元素并将其保存在一个新的字典中。

The new Dict should be look like:

新的字典应该是这样的:

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

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

采纳答案by Sven Marnach

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)

If you want to avoid the use of defaultdict, you could also do

如果你想避免使用defaultdict,你也可以这样做

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

回答by Adam Lear

Here's a naive implementation. Someone with better Python skills can probably make it more concise and awesome.

这是一个幼稚的实现。拥有更好 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

This produces

这产生

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

回答by pcurry

If you do specifically want tuples as the values in your new dictionary, you can still use defaultdict, and use tuple concatenation. This solution works in Python 3.4+:

如果你特别想要元组作为你新字典中的值,你仍然可以使用 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)

Which will produce

哪个会产生

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

This will probably be slower than generating a dictionary by list insertion, and will create more objects to be collected. So, you can build your dictionary out of lists, and then map it into tuples:

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

target2 = defaultdict(list)

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

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

print(target2)

Which will give the same result as above.

这将产生与上述相同的结果。