To detect all of these cases:
>>> import collections >>> d = {"a": 10, "b": 15, "c": 10} >>> value_to_key = collections.defaultdict(list) >>> for k, v in d.iteritems(): ... value_to_key[v].append(k) ... >>> value_to_key defaultdict(<type 'list'>, {10: ['a', 'c'], 15: ['b']})
@hivert makes a great point that this only works if the values โโare hashed. If this is not the case, then there is no good O (n) solution (unfortunately). This is the best I can think of:
d = {"a": [10, 15], "b": [10, 20], "c": [10, 15]} values = [] for k, v in d.iteritems(): must_insert = True for val in values: if val[0] == v: val[1].append(k) must_insert = False break if must_insert: values.append([v, [k]]) print [v for v in values if len(v[1]) > 1]
source share