Dict Comprehension:如果有密钥存在,则追加到密钥值,如果不存在密钥,则创建新的key:value对

时间:2020-03-13 09:59:42

标签: python dictionary list-comprehension dictionary-comprehension

我的代码如下:

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

其中data是这样排列的列表的列表:

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

我想要的结果是:

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

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

2 个答案:

答案 0 :(得分:4)

可以使用dict.setdefaultcollections.defaultdict

简化此操作

例如:

data = [["a",100],["b",200],["a",50]]
res = {}   #or collections.defaultdict(list)
for k, v in data:
    res.setdefault(k, []).append(v)  #if defaultdict use res[k].append(v)

print(res)

输出:

{'a': [100, 50], 'b': [200]}

答案 1 :(得分:-1)

您可以将.update用于字典。

data = [["a",100],["b",200],["a",50]]
dictionary = dict()

for user,score in data:
    if user in dictionary.keys():
        dictionary[user] += [score]
    else:
        dictionary.update({user:[score]})

输出:

{'a': [100, 50], 'b': [200]}