I am trying to split a list of strings into a dict some of these strings end up been duplicate keys after they are split, my end goal is to split the list then sum up the values for each key. I have the following code that works, however I receive a ValueError: too many values to unpack (expected 2). when the list contains a negative integer. How would I go about fixing this.
v=["a:1", "b:3", "c:5","c:3"]
list_of_str = list(map(lambda elem: elem.replace(":", ''), v))
list_of_str
from collections import defaultdict
my_dict = defaultdict(list)
for k, v in list_of_str:
my_dict[k].append(v)
my_dict
defaultdict(list, {'a': ['1'], 'b': ['3'], 'c': ['5', '3']})
Result with negative value in the list
v=["a:1", "b:3", "c:5","c:-3"]
list_of_str = list(map(lambda elem: elem.replace(":", ''), v))
list_of_str
ā
from collections import defaultdict
my_dict = defaultdict(list)
for k, v in list_of_str:
my_dict[k].append(v)
my_dict
ValueError Traceback (most recent call last)
<ipython-input-48-7a8d435becbb> in <module>
5 from collections import defaultdict
6 my_dict = defaultdict(list)
----> 7 for k, v in list_of_str:
8 my_dict[k].append(v)
9 my_dict
ValueError: too many values to unpack (expected 2)
The result I am going for:
defaultdict(list, {'a': ['1'], 'b': ['3'], 'c': ['5', '3']})
a:1,b:3,c:8