I have a list of items and values:
users_lst = [' spotify: 50.4\n', 'pandora: 23.4\n', 'pandora: 22.1\n', '\n', 'applemusic: \n]
I want to convert it to a dictionary, like this:
users = {'spotify': 50.4, 'pandora': 45.5}
My current code doesn't sum up the values for pandora:
users_lst = ['spotify: 50.4\n', 'pandora: 23.4\n', 'pandora: 22.1\n']
for i in users_lst:
i = i.split(':')
key = i[0]
value = i[1]
users[key] = value
print(users) #output: {'spotify': ' 50.4\n', 'applemusic': ' 22.1\n'}
Any pointers would be much appreciated. Prefer to use a solution without importing modules.
*Edit: updated the list to include non-float-type, blank and leading/trailing space cases
I can use a simple for loop and bunch of string cleaning operations like this to solve the problem,
users_lst = ['spotify: 50.4\n', 'pandora: 23.4\n', 'pandora: 22.1\n']
d = dict()
for item in users_lst:
key, val = item.split(":")
val = float(val.strip().replace("\n", ""))
if key not in d:
d[key] = val
else:
d[key] = d[key] + val
print(d) # {'spotify': 50.4, 'pandora': 45.5}
You can use dict.get() method and eliminate the use of if else checks like this,
users_lst = ['spotify: 50.4\n', 'pandora: 23.4\n', 'pandora: 22.1\n']
d = dict()
for item in users_lst:
key, val = item.split(":")
d[key] = d.get(key, 0) + float(val)
print(d) # {'spotify': 50.4, 'pandora': 45.5}
Using collections.defaultdict
Ex:
from collections import defaultdict
users_lst = ['spotify: 50.4\n', 'pandora: 23.4\n', 'pandora: 22.1\n']
result = defaultdict(float)
for i in users_lst:
key, value = i.strip().split(":")
result[key] += float(value)
print(result) # OR print(dict(result))
Output:
defaultdict(<class 'float'>, {'spotify': 50.4, 'pandora': 45.5})
There is many way to do this:
users_lst = ['spotify: 50.4\n', 'pandora: 23.4\n', 'pandora: 22.1\n']
user = dict()
for item in users_lst:
key, val = item.split(":")
val = float(val.strip())
user[key] = user.get(key,0)+value
for i in users_lst:
key, value = i.strip().split(':')
users[key] = users.get(key, 0.0) + float(value)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.