Python 查找具有重复值的字典键

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

Find dictionary keys with duplicate values

pythondictionary

提问by lzc

some_dict = {"firstname": "Albert", "nickname": "Albert", "surname": "Likins", "username": "Angel"}

I would like to return the keys of my dict where their value exists for more than one time.

我想返回我的字典的键,它们的值存在不止一次。

Could some one show me how to implement this?

有人可以告诉我如何实现这一点吗?

a_list = []
for k,v in  some_dict.iteritems():
    if v in some_dict.values() and v != some_dict.keys(k):
        a_list.append(k)

采纳答案by abarnert

First, flip the dictionary around into a reverse multidict, mapping each value to all of the keys it maps to. Like this:

首先,将字典翻转为反向多重字典,将每个值映射到它映射到的所有键。像这样:

>>> some_dict = {"firstname":"Albert","nickname":"Albert","surname":"Likins","username":"Angel"}
>>> rev_multidict = {}
>>> for key, value in some_dict.items():
...     rev_multidict.setdefault(value, set()).add(key)

Now, you're just looking for the keys in the multidict that have more than 1 value. That's easy:

现在,您只是在 multidict 中查找值超过 1 的键。这很容易:

>>> [key for key, values in rev_multidict.items() if len(values) > 1]
['Albert']

Except the multidict keys are the original dict values. So, this is each repeated value, not all of the keys matching each repeated value. But you know what isall of the keys matching each repeated value?

除了 multidict 键是原始的 dict 值。因此,这是每个重复值,而不是与每个重复值匹配的所有键。但是您知道匹配每个重复值的所有键什么吗?

>>> [values for key, values in rev_multidict.items() if len(values) > 1]
[{'firstname', 'nickname'}]

Of course that gives you a list of sets. If you want to flatten that into a single list or set, that's easy. You can use chain.from_iterable, or a nested comprehension, or any of the other usual tricks. For example:

当然,这会给你一个集合列表。如果您想将其展平为单个列表或集合,那很容易。您可以使用chain.from_iterable、嵌套理解或任何其他常用技巧。例如:

>>> set(chain.from_iterable(values for key, values in rev_multidict.items() if len(values) > 1))
{'firstname', 'nickname'}

回答by Blender

I would start by flipping the keys and values:

我首先翻转键和值:

flipped = {}

for key, value in d.items():
    if value not in flipped:
        flipped[value] = [key]
    else:
        flipped[value].append(key)

You could do this more efficiently with collections.defaultdict(set). For your dictionary, flippedwill look like:

您可以使用collections.defaultdict(set). 对于您的字典,flipped将如下所示:

{
    'Albert': ['nickname', 'firstname'],
    'Angel':  ['username'],
    'Likins': ['surname']
}

回答by Igor Fobia

This method does not require neither external libraries nor an ifstatement:

此方法既不需要外部库也不需要if语句:

    reverse_dic = {}
    for k, v in original_dic.iteritems():
        reverse_dic[v] = reverse_dic.get(v, [])
        reverse_dic[v].append(k)

回答by user2005685

If your data set isn't too large, you don't need reverse multidict. You can use count on dict.values() and return the desired keys by iterating over dict.items().

如果您的数据集不是太大,则不需要反向多重字典。您可以在 dict.values() 上使用 count 并通过迭代 dict.items() 返回所需的键。

desired_keys = []

vals = some_dict.values()

for key, value in some_dict.items():
   if vals.count(value) > 1:
        desired_keys.append(key)

Hope this helps!

希望这可以帮助!

回答by HanByul Lee

This method uses 'try' and 'for'.

此方法使用“try”和“for”。

original data

原始数据

original_dict = {"firstname":"Albert", "nickname":"Albert", "surname":"Likins", "username":"Angel"}

code

代码

reverse_dict = {}
for key, value in original_dict.items():
    try:reverse_dict[value].append(key)
    except:reverse_dict[value] = [key]

result

结果

>>> reverse_dict
{'Albert': ['firstname', 'nickname'], 'Likins': ['surname'], 'Angel': ['username']}

>>> [value for key, value in reverse_dict.items() if len(value) > 1]
[['firstname', 'nickname']]

回答by nvd

Using "defaultdict":

使用“defaultdict”:

from collections import defaultdict

s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = defaultdict(list)

for k, v in s:
    d[k].append(v)

for key, value in d.items():
    if len(value) > 1:
        print "key: %s has multiple values: %r" % (key, value)