Creating a dictionary from a list

There is a list:

List= ["sugar:10", "coffee:23", "sugar:47", "salt:26"]

From this list I need to get a dictionary:

Dict = {"sugar":57, "coffee":23, "salt":26}

I used to do some similar examples, but with this I have only a general idea (first break the list), and if there is the same key for two values, I need to add them.

Can someone help and let me know how to solve this?

+4
source share
5 answers

This can be easily achieved with 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})
+6
source

You can do funny 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 might be a better fit.

r = Counter()
for x in lst:
    r.update(f(x))

r
Counter({'coffee': 23, 'salt': 26, 'sugar': 57})
+4
source
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])
0

.

from collections import defaultdict
d = defaultdict(int)
b = map(lambda x: (x[0], int(x[1])), [x.split(':') for x in li])
for k, v in b:
    d[k] += v

>>>d
defaultdict(<type 'int'>, {'coffee': 23, 'salt': 26, 'sugar': 57})
0

Dict , .

:

>>> 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}
-1

Source: https://habr.com/ru/post/1689898/


All Articles