Python: finding keys with unique values in a dictionary?

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

    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
    

提交回复
热议问题