我有一本字典如下:
mydict = {'HEALTH': {'NumberOfTimes': 2, 'Score': 12},
'branch': {'NumberOfTimes': 4, 'Score': 34},
'transfer': {'NumberOfTimes': 1, 'Score': 5},
'deal': {'NumberOfTimes': 1, 'Score': 10}}
我想将Score
除以NumberOfTimes
中每个键的mydict
,并将其保存在一个列表或另一个字典中。目标是:
newdict = {word:'HEALTH', 'AvgScore': 6},
{word:'branch': 4, 'AvgScore': 8.5},
{word:'transfer', 'AvgScore': 5},
{word:'deal', 'AvgScore': 10}}
我对后者的代码如下:
newdict = {}
for k, v in mydict.items():
newdict[k]['AvgScore'] = v['Score']/v['NumberOfTimes']
但这会产生错误KeyError: 'HEALTH'
我也尝试了以下方法:
from collections import defaultdict
newdict = defaultdict(dict)
for k, v in mydict.items():
newdict[k]['AvgScore'] = v['Score']/v['NumberOfTimes']
这里我得到以下错误:
---------------------------------------------------------------------------
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
如何将键值对添加到新词典中
使用简单的迭代
演示:
输出:
试试这个:
相关问题 更多 >
编程相关推荐