Python: finding keys with unique values in a dictionary?

前端 未结 9 1980
臣服心动
臣服心动 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:30

    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.

提交回复
热议问题