【问题标题】:How do I insert new items in a blank dictionary in Python 3?如何在 Python 3 的空白字典中插入新项目?
【发布时间】:2018-07-05 09:35:50
【问题描述】:

我有一本字典如下:

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

对于mydict 中的每个键,我想将Score 除以NumberOfTimes,并将其保存在列表或另一个字典中。目标是:

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

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

【问题讨论】:

  • for k, v in mydict.items():替换for k, v in word_vec.items():
  • 对于第一个错误KeyError: 'HEALTH',尝试使用update添加新键,如果你有嵌套的dicts,你应该通过youdict.update添加所有级别。
  • 问题是你尝试设置一个像newdict[k]['AvgScore']这样的嵌套字典。请参阅this post 了解实现这种行为的方法。

标签: python dictionary indexing key-value


【解决方案1】:

试试这个:

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

【讨论】:

  • 在我的实际字典中(我只显示了其中的前 4 个键值对,但它有 2596 个键值对),您的代码出现以下错误:TypeError: string indices must be integersword_vec_avg[k] = {"word": k, 'AvgScore': v['Score']/v['NumberOfTimes']} 行,虽然当我尝试打印新字典时,我看到它包含 2404 项。
【解决方案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}]

【讨论】:

  • 在我的实际字典中(我只显示了其中的前 4 个键值对,但它有数千个),我的代码出现以下错误:TypeError: string indices must be integers 在线 @987654324 @
  • 是的。事实上,当我像这里一样复制mydict 中的前4个条目时,没有错误。仅在获取完整字典时才会出现错误。
  • 看起来你的字典中有一个列表。请检查您的 dict 值
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-28
  • 1970-01-01
相关资源
最近更新 更多