Making Dictionary out of List

Viewed 165

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?

5 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})

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})
mydict={}
for i in List:
    splited=i.split(":")
    if(splited[0] in mydict):
        mydict[splited[0]]+=int(splited[1])
    else:
        mydict[splited[0]]=int(splited[1])

Since Dict gets a list in its constructor, you can simple generate one out of your list on the fly.

Here it is:

>>> from collections import defaultdict
>>> l = ["sugar:10", "coffee:23", "sugar:47", "salt:26"]
>>> items = (i.split(":") for i in l)
>>> d = defaultdict(int)
>>> for i in items:
...     d[i[0]]+= int(i[1])
>>> dict(d)
{'coffee': 23, 'salt': 26, 'sugar': 57}
Related