The current lead answer suggests that the values โโare unique, which is not always the case. What if the values โโare not unique? You will lose information! For example:
d = {'a':3, 'b': 2, 'c': 2} {v:k for k,v in d.iteritems()}
returns {2: 'b', 3: 'a'} .
Information about 'c' been completely ignored. Ideally, this should have been something like {2: ['b','c'], 3: ['a']} . This is what the bottom implementation does.
def reverse_non_unique_mapping(d): dinv = {} for k, v in d.iteritems(): if v in dinv: dinv[v].append(k) else: dinv[v] = [k] return dinv
Hanan Shteingart Aug 03 '17 at 23:20 2017-08-03 23:20
source share