I have a dictionary as follows:
mydict = {'HEALTH': {'NumberOfTimes': 2, 'Score': 12},
'branch': {'NumberOfTimes': 4, 'Score': 34},
'transfer': {'NumberOfTimes': 1, 'Score': 5},
'deal': {'NumberOfTimes': 1, 'Score': 10}}
I want to divide the Score
by NumberOfTimes
for each key in mydict
, and save it in either a list or another dictionary. The goal is to have the following:
newdict = {word:'HEALTH', 'AvgScore': 6},
{word:'branch': 4, 'AvgScore': 8.5},
{word:'transfer', 'AvgScore': 5},
{word:'deal', 'AvgScore': 10}}
My code for the latter is as follows:
newdict = {}
for k, v in mydict.items():
newdict[k]['AvgScore'] = v['Score']/v['NumberOfTimes']
But this gives the error KeyError: 'HEALTH'
.
I tried the following as well:
from collections import defaultdict
newdict = defaultdict(dict)
for k, v in mydict.items():
newdict[k]['AvgScore'] = v['Score']/v['NumberOfTimes']
Here I get the following error:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-237-d6ecaf92029c> in <module>()
4 # newdict = {}
5 for k, v in mydict.items():
----> 6 newdict[k]['AvgScore'] = v['Score']/v['NumberOfTimes']
7
8 #sorted(newdict.items())
TypeError: string indices must be integers
How do I add the key-value pairs into a new dictionary?