简体   繁体   中英

Append to list in python dict comprehension

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?

A more sophisticated way to do it:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM