0

This is my first time asking a question on stack overflow myself but have been using the resources here for quite a while - thanks!

list_1 = ['a','b','c','c']
list_2 = [2,2,2,2]

I want to combine both the lists and get add values of the same keys

my_dict = dict(zip(stream_ids, times))

but whenever I combine the lists to dictionaries - value for the key gets replaced by the last one

Output: {'a': 2, 'b': 2, 'c': 2} 

I want both 'c' to be added to get a 4 What I want to get is

{'a': 2, 'b': 2, 'c': 4} 

Any help would be really appreciated!

Mark
  • 90,562
  • 7
  • 108
  • 148

3 Answers3

0

The most readable way would be to use a simple for loop:

stream_ids = ['a','b','c','c']
times = [2,2,2,2]
my_dict = {}
for idx, count in zip(stream_ids, times):
    if idx in dict:
        my_dict[idx] += count
    else:
        my_dict[idx] = count

You can probably do it in one line too using a lamda function and dictionary comprehension but that won't be very readable.

kinshukdua
  • 1,944
  • 1
  • 5
  • 15
0

A dict will simply overwrite existing values. You have to build your dict by your own.

stream_ids = ['a','b','c','c']
times = [2,2,2,2]
my_dict = {}
for s, t in zip(stream_ids, times):
    my_dict[s] = my_dict.get(s, 0) + t

print(my_dict)  # {'a': 2, 'b': 2, 'c': 4}
Sven Eberth
  • 3,057
  • 12
  • 24
  • 29
0

A variant of other answers here, with collections.defaultdict:

from collections import defaultdict
stream_ids = ['a','b','c','c']
times = [2,2,2,2]
dict = defaultdict(int)
for idx, count in zip(stream_ids, times):
    dict[idx] += count

since the default for a new integer is 0.

9769953
  • 10,344
  • 3
  • 26
  • 37