Issue
A list of strings, that part of the string, is a key in the dictionary. I want to return values from a dictionary by the keys, then sum the values.
d = {"2016_05" : 665,
"2016_04" : 462,
"2015_03" : 568,
"2015_08" : 895}
for a in ['Toyota_2015_03', 'Toyota_2015_04', 'Kia_2016_01', 'Kia_2016_04', 'Kia_2016_05']:
name, year, month = a.split('_')
sales = d.get(year + '_' + month)
if sales is not None:
print (name + '_' + str(sales))
output:
Toyota_568
Kia_462
Kia_665
I want to sum the number by 'Kia' and 'Toyota' (i.e. some form to get Kia:1127, Toyota:568). What is the good way to proceed?
Solution
Use another dict to sum the sales. You can use dict.get()
with default value to simulate defaultdict
all_sales = {}
for a in ['Toyota_2015_03', 'Toyota_2015_04', 'Kia_2016_01', 'Kia_2016_04', 'Kia_2016_05']:
name, year, month = a.split('_')
sales = d.get(year + '_' + month, 0)
if sales: # can be removed if you don't have car types with no sales or you want to see those cars
all_sales[name] = all_sales.get(name, 0) + sales
print(all_sales)
Output
{'Toyota': 568, 'Kia': 1127}
Answered By - Guy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.