Python:在字典中查找具有唯一值的键?

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

Python: finding keys with unique values in a dictionary?

pythondictionary

提问by Roee Adler

I receive a dictionary as input, and want to return a list of keys for which the dictionary values are unique in the scope of that dictionary.

我收到一个字典作为输入,并希望返回一个键列表,其中的字典值在该字典的范围内是唯一的。

I will clarify with an example. Say my input is dictionary a, constructed as follows:

我会用一个例子来澄清。假设我的输入是字典a,构造如下:

a = dict()
a['cat'] =      1
a['fish'] =     1
a['dog'] =      2  # <-- unique
a['bat'] =      3
a['aardvark'] = 3
a['snake'] =    4  # <-- unique
a['wallaby'] =  5
a['badger'] =   5  

The result I expect is ['dog', 'snake'].

我期望的结果是['dog', 'snake']

There are obvious brute force ways to achieve this, however I wondered if there's a neat Pythonian way to get the job done.

有明显的蛮力方法可以实现这一点,但是我想知道是否有一种简洁的 Pythonian 方法来完成工作。

采纳答案by Anurag Uniyal

I think efficient way if dict is too large would be

如果 dict 太大,我认为有效的方法是

countMap = {}
for v in a.itervalues():
    countMap[v] = countMap.get(v,0) + 1
uni = [ k for k, v in a.iteritems() if countMap[v] == 1]

回答by Bartosz Radaczyński

Note that this actually is a bruteforce:

请注意,这实际上是一种蛮力:

l = a.values()
b = [x for x in a if l.count(a[x]) == 1]

回答by Rick Copeland

Here is a solution that only requires traversing the dict once:

这是一个只需要遍历 dict 一次的解决方案:

def unique_values(d):
    seen = {} # dict (value, key)
    result = set() # keys with unique values
    for k,v in d.iteritems():
        if v in seen:
            result.discard(seen[v])
        else:
            seen[v] = k
            result.add(k)
    return list(result)

回答by John Machin

>>> b = []
>>> import collections
>>> bag = collections.defaultdict(lambda: 0)
>>> for v in a.itervalues():
...     bag[v] += 1
...
>>> b = [k for (k, v) in a.iteritems() if bag[v] == 1]
>>> b.sort() # optional
>>> print b
['dog', 'snake']
>>>

回答by Juergen

A little more verbose, but does need only one pass over a:

稍微冗长一点,但只需要一次通过:

revDict = {}
for k, v in a.iteritems():
  if v in revDict:
     revDict[v] = None
  else:
     revDict[v] = k

[ x for x in revDict.itervalues() if x != None ]

( I hope it works, since I can't test it here )

(我希望它有效,因为我无法在这里测试)

回答by fabrizioM

What about subclassing?

子类化呢?

class UniqueValuesDict(dict):

    def __init__(self, *args):
        dict.__init__(self, *args)
        self._inverse = {}

    def __setitem__(self, key, value):
        if value in self.values():
            if value in self._inverse:
                del self._inverse[value]
        else:
            self._inverse[value] = key
        dict.__setitem__(self, key, value)

    def unique_values(self):
        return self._inverse.values()

a = UniqueValuesDict()

a['cat'] =      1
a['fish'] =     1
a[None] =       1
a['duck'] =     1
a['dog'] =      2  # <-- unique
a['bat'] =      3
a['aardvark'] = 3
a['snake'] =    4  # <-- unique
a['wallaby'] =  5
a['badger'] =   5

assert a.unique_values() == ['dog', 'snake']

回答by S.Lott

Here's another variation.

这是另一种变体。

>>> import collections
>>> inverse= collections.defaultdict(list)
>>> for k,v in a.items():
...     inverse[v].append(k)
... 
>>> [ v[0] for v in inverse.values() if len(v) == 1 ]
['dog', 'snake']

I'm partial to this because the inverted dictionary is such a common design pattern.

我偏爱这个,因为倒排字典是一种很常见的设计模式。

回答by Alex Morega

You could do something like this (just count the number of occurrences for each value):

你可以做这样的事情(只需计算每个值的出现次数):

def unique(a):
    from collections import defaultdict
    count = defaultdict(lambda: 0)
    for k, v in a.iteritems():
        count[v] += 1
    for v, c in count.iteritems():
        if c <= 1:
            yield v

回答by Greg Bacon

Use nested list comprehensions!

使用嵌套列表理解!

print [v[0] for v in 
           dict([(v, [k for k in a.keys() if a[k] == v])
                     for v in set(a.values())]).values()
       if len(v) == 1]