如何在python3的空白字典中插入新项?

2024-06-29 01:13:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本字典如下:

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

如何将键值对添加到新词典中


Tags: inbranchfor字典错误itemsmydictword
2条回答

使用简单的迭代

演示:

mydict = {'HEALTH': {'NumberOfTimes': 2, 'Score': 12},
 'branch': {'NumberOfTimes': 4, 'Score': 34},
 'transfer': {'NumberOfTimes': 1, 'Score': 5},
 'deal': {'NumberOfTimes': 1, 'Score': 10}}

newdict = {}
for k, v in mydict.items():
    newdict[k] = {"word": k, 'AvgScore': v['Score']/v['NumberOfTimes']}
print(newdict.values())

输出:

[{'word': 'transfer', 'AvgScore': 5}, {'word': 'HEALTH', 'AvgScore': 6}, {'word': 'branch', 'AvgScore': 8}, {'word': 'deal', 'AvgScore': 10}]

试试这个:

mydict = {'HEALTH': {'NumberOfTimes': 2, 'Score': 12},
 'branch': {'NumberOfTimes': 4, 'Score': 34},
 'transfer': {'NumberOfTimes': 1, 'Score': 5},
 'deal': {'NumberOfTimes': 1, 'Score': 10}}

word_vec_avg = {}
for k, v in mydict.items():
        word_vec_avg[k]={'AvgScore':v['Score']/v['NumberOfTimes']} #create a new dict and assign

相关问题 更多 >