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}
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}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With