Python: finding keys with unique values in a dictionary?

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

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

    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)
    

提交回复
热议问题