2

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?

  • 3
    a solution as a comprehension would not be efficient in this case, why this constraint? – mozway Jan 18 '22 at 15:06
  • 1
    You could use `collections.defaultdict` though so you won't need the `if` `else`. – ssp Jan 18 '22 at 15:26
  • [It is possible but extremely ugly](https://stackoverflow.com/a/18520982/10166393) – ssp Jan 18 '22 at 15:30

2 Answers2

3

A more sophisticated way to do it:

out = {}
for key, val in inp.items():
    out.setdefault(val, []).append(key)
0

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.

vaizki
  • 1,678
  • 1
  • 9
  • 12