Python: finding keys with unique values in a dictionary?

前端 未结 9 2042
臣服心动
臣服心动 2021-02-19 01:28

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 exa

9条回答
  •  南笙
    南笙 (楼主)
    2021-02-19 01:35

    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']
    

提交回复
热议问题