There is a list given:
List= ["sugar:10", "coffee:23", "sugar:47", "salt:26"]
From that list I need to get dictionary:
Dict = {"sugar":57, "coffee":23, "salt":26}
I did some similar examples before, but with this one I only have general idea (to split list first) and if there is same key for 2 values I need to add them together.
Can someone pleas help and give me idea how to solve this?
You can achieve this pretty easily with a defaultdict
:
from collections import defaultdict
li = ["sugar:10", "coffee:23", "sugar:47", "salt:26"]
d = defaultdict(int)
for item in li:
split_item = item.split(':')
d[split_item[0]] += int(split_item[1])
print(d)
# defaultdict(<class 'int'>, {'sugar': 57, 'coffee': 23, 'salt': 26})
You can do fun things with Counter
s!
from collections import Counter
def f(x):
x, y = x.split(':')
return Counter({x : int(y)})
sum(map(f, lst), Counter())
Counter({'coffee': 23, 'salt': 26, 'sugar': 57})
If you're concerned about performance, a loop may be better suited.
r = Counter()
for x in lst:
r.update(f(x))
r
Counter({'coffee': 23, 'salt': 26, 'sugar': 57})
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