How to avoid looking-up a dictionary twice for getting/setting key value in Python?

entropyfeverone :

I have a list:

lst = [('a', 1), ('b', 2), ('c', 3), ('a', 4), ('c', 5)]

and I want to group by the first element of the tuple and append the second element:

group = {'a': [1, 4], 'b': [2], 'c': [3, 5]}

So my code looks like this:

group = dict()
for e1, e2 in lst:
    if e1 in group:
        group[e1].append(e2)
    else:
        group[e1] = [e2]

What I don't like about this code is that I am looking up for a key in the group dictionary twice, one for the command e1 in group and two for the command group[e1] = ...

Is there a better way to keep 'a pointer' if the key is found and don't have to look a second time to set the value of this key?
Also, if there is a far better solution using a library please let me know.

Ch3steR :

You can use defaultdict.

from collections import defaultdict
lst = [('a', 1), ('b', 2), ('c', 3), ('a', 4), ('c', 5)]
group=defaultdict(list)

for k,v in lst:
    group[k].append(v)

group
# defaultdict(list, {'a': [1, 4], 'b': [2], 'c': [3, 5]})

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=193477&siteId=1