本文介绍了查找具有重复值的字典键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我想返回我的dict的密钥,其值存在一次以上。



可能有人告诉我如何实现这个?

  a_list = [] 
for k,v in some_dict .iteritems():
如果v in some_dict.values()和v!= some_dict.keys(k):
a_list.append(k)
/ pre>

解决方案

首先,将字典翻转成一个反向多维度,将每个值映射到其映射到的所有键。像这样:

 >>> some_dict = {firstname:Albert,nickname:Albert,surname:Likins,username:Angel} 
>>> rev_multidict = {}
>>>对于key,在some_dict.items()中的值:
... rev_multidict.setdefault(value,set())。add(key)

现在,您只是在多单元格中找到具有超过1个值的键。很简单:

 >>> [key for key,rev_multidict.items()中的值如果len(values)> 1] 
['Albert']

除了多重键是原始的dict值。所以,这是每个重复的值,并不是所有的键匹配每个重复的值。但是你知道什么是所有匹配每个重复值的键?

 >> ; [key的值,rev_multidict.items()中的值,如果len(values)> 1] 
[{'firstname','nickname'}]

当然,你的集合列表如果你想把它变成一个单一的列表或集合,那很简单。您可以使用 chain.from_iterable ,或嵌套理解,或任何其他常规技巧。例如:

 >>> set(chain.from_iterable(key的值,rev_multidict.items()中的值,如果len(values)> 1))
{'firstname','nickname'}


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)
解决方案

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:

>>> [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 is all of the keys matching each repeated value?

>>> [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:

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

这篇关于查找具有重复值的字典键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 22:50