Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

two lists into a dictionary

I have two lists created in python like so:

list1 = [2, 3, 3, 4, 4, 5]
list2 = [-4, 8, -4, 8, -1, 2]

Now I zipped these two lists into a dictionary like so:

d = dict(zip(list1, list2))

which gives me:

{2: -4, 3: -4, 4: -1, 5: 2}

What I want to get is a result like this:

{2: -4, 3: 4, 4: 7, 5: 2}

list1 is becoming the the keys to the new dictionary. If I have two values in list1 that are the same, I want it to add the two values. For example, in list2, 8 and -4 both have the same key 3. Is there a way to add these two values together so the key looks like

{3: 4}   
like image 354
me45 Avatar asked Dec 04 '22 06:12

me45


2 Answers

I think you want something like this:

>>> list1 = [2, 3, 3, 4, 4, 5]
>>> list2 = [-4, 8, -4, 8, -1, 2]

>>> d = {}
>>> for k, v in zip(list1, list2):
        d[k] = d.get(k, 0) + v

>>> d
{2: -4, 3: 4, 4: 7, 5: 2}
like image 151
Raymond Hettinger Avatar answered Dec 14 '22 22:12

Raymond Hettinger


Try using a defaultdict:

from collections import defaultdict

d = defaultdict(int)
for k, v in zip(list1, list2):
    d[k] += v

Result:

defaultdict(<type 'int'>, {2: -4, 3: 4, 4: 7, 5: 2})

See it working online: ideone

like image 31
Mark Byers Avatar answered Dec 14 '22 22:12

Mark Byers