Search code examples
pythondictionarylist-comprehensiondictionary-comprehension

Dict Comprehension: appending to a key value if key is present, create a new key:value pair if key is not present


My code is as follows:

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

where data is a list of lists arranged as such:

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

and the result i want is:

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

Would it be possible to do this with a single dictionary comprehension?


Solution

  • This can be simplified using dict.setdefault or collections.defaultdict

    Ex:

    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)
    

    Output:

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