I have 2 dictionaries
how can i get a dictionary that has the values divided buy the the value of the same key but in the other dictionary ?
stat_dict = {'good': 6537048, 'evil': 32000, 'neutral': 69467, 'nihilist': 81977, 'cool': 771180}
count_dict = {'good': 2, 'evil': 2, 'neutral': 2, 'nihilist': 2, 'cool': 2}
this what I am looking for an example for 'good'
avg_dict = {'good': 6537048/2}
i wrote this
avg_dict = {k:stat_dict[s_lst[2]]/count_dict[s_lst[2]] for k,v in stat_dict.items()}
but this gave
{'good': 385590.0, 'evil': 385590.0, 'neutral': 385590.0, 'nihilist': 385590.0, 'cool': 385590.0}
CodePudding user response:
Can't you just do:
for key in stat_dict.keys():
avg_dict[key] = stat_dict[key]/count_dict[key]
?
Or are there keys in stat_dict that won't be in count_dict?
CodePudding user response:
What you're looking for is the Dict items method.
This will give you access to the key and value in your first dictionary:
{ key: value / count_dict[key] for (key, value) in stat_dict.items() }
See Python Dictionary Comprehension for more!
CodePudding user response:
You could simply use a dictionary comprehension:
{k:v/count_dict[k] for k,v in stat_dict.items()}
output:
{'good': 3268524.0,
'evil': 16000.0,
'neutral': 34733.5,
'nihilist': 40988.5,
'cool': 385590.0}
CodePudding user response:
Try:
avg_dict = {k:v/count_dict[k] for k,v in stat_dict.items()}