python - 如何在 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
如何将键值对添加到新字典中?
解决方案
使用简单的迭代。
演示:
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}]
推荐阅读
- sql-server - SQL Server 扩展事件找不到指定的路径
- c# - 如何在c#中裁剪倾斜图像
- c - 简单的 C 程序来说明乱序执行?
- android - 如何在使用不同风格的相同命名类时防止重复类错误?
- ms-access - 通过在字段中增加一个工作日,其余为空白,在访问表单中添加新记录
- java - bindservice 不会启动服务并且 onserviceconnect 不会调用
- dart - 在 dart 中的 MultipartRequest 中添加授权标头
- batch-file - 从 FTP 删除多个文件
- android - React Native / Android:显示高分辨率图像
- python - Keras:在一个简单的网络中,“一个操作对于梯度没有`None`”