Suppose we have a dictionary inp = {"virat":60,"rohit":50,"sardhul":50,"rana":60} and
we should get the output as {60: ['virat', 'rana'], 50: ['rohit', 'sardhul']}
I can do it in normal python programming as follows
out = dict()
for key, val in inp.items():
if val not in out:
out[val] = [key]
else:
out[val].append(key)
The output is {60: ['virat', 'rana'], 50: ['rohit', 'sardhul']}
How can we do the same in dictionary comprehension?
CodePudding user response:
A more sophisticated way to do it:
out = {}
for key, val in inp.items():
out.setdefault(val, []).append(key)
CodePudding user response:
As mentioned by others, it is not efficient but if you MUST have a comprehension:
{ val: [ key for key,vv in inp.items() if vv == val ] for val in inp.values() }
This is basically equivalent to:
out = dict()
for val in inp.value():
tmp = list()
for key,vv in inp.items():
if vv == val:
tmp.append(key)
out[val] = tmp
... which is a lot less efficient than your original code.
