首页 > 解决方案 > 如何在 Python 3 的空白字典中插入新项目?

问题描述

我有一本字典如下:

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

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

标签: pythondictionaryindexingkey-value

解决方案


使用简单的迭代。

演示:

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}]

推荐阅读