Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making Dictionary out of List

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?

like image 943
noca951 Avatar asked Jan 29 '23 03:01

noca951


2 Answers

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})
like image 174
DeepSpace Avatar answered Jan 31 '23 18:01

DeepSpace


You can do fun things with Counters!

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})
like image 36
cs95 Avatar answered Jan 31 '23 18:01

cs95