Dict理解:如果存在key,则附加到键值,如果不存在key,则创建一个新的key:value对]]

问题描述 投票:0回答:2

我的代码如下:

for user,score in data:
    if user in res.keys():
        res[user] += [score]
    else:
        res[user] = [score]

其中数据是这样排列的列表的列表:

data = [["a",100],["b",200],["a",50]] 

我想要的结果是:

res = {"a":[100,50],"b":[200]}

是否可以通过单个字典理解来做到这一点?

我的代码如下:对于用户,数据得分:如果用户在res.keys()中:res [user] + = [score]否则:res [user] = [score]其中data是列表的列表排列方式如下:data = [...

python dictionary list-comprehension dictionary-comprehension
2个回答
4
投票

可以用dict.setdefaultcollections.defaultdict简化


-1
投票

您可以将.update用于字典。.

© www.soinside.com 2019 - 2024. All rights reserved.