[英]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']}
假设我们有一个字典
inp = {"virat":60,"rohit":50,"sardhul":50,"rana":60}
我们应该得到 output 为{60: ['virat', 'rana'], 50: ['rohit', 'sardhul']}
I can do it in normal python programming as follows我可以在正常的 python 编程中做到这一点,如下所示
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']}
output 是
{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. ...这比您的原始代码效率低得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.