【问题标题】:Add item to nested dictionary using for loop使用 for 循环将项目添加到嵌套字典
【发布时间】:2020-02-09 18:52:40
【问题描述】:

我正在尝试使用 for 循环在嵌套字典中添加一个项目。该项目应该在内部字典中,因此它显示为项目'Aggressive': True 之后的一个项目,并且在每个内部字典中,即'Gold-crested Toucan' 和'Pearlescent Kingfisher'。

rarebirds = {
    'Gold-crested Toucan': {
        'Height (m)': 1.1,
        'Weight (kg)': 35,
        'Aggressive': True},
    'Pearlescent Kingfisher': {
        'Height (m)': 0.25,
        'Weight (kg)': 0.5,
        'Aggressive': False},
}
#my most recent attempt below, although I've tried using .update as well as i and j dics within the loop

for key in rarebirds:
    rarebirds[key]['Seen'] == False

输出是KeyError: 'Seen'

对于这个简单问题的建议将不胜感激。

【问题讨论】:

  • 欢迎来到 Stack Overflow!查看tour 和How to Ask。我投票结束这个问题,因为最终这是一个错字,== 与 =,但别担心,它发生在每个人身上:)

标签: python python-3.x dictionary nested


【解决方案1】:
rarebirds = {
    "Gold-crested Toucan": {
        "Height (m)": 1.1,
        "Weight (kg)": 35,
        "Aggressive": True
    },
    "Pearlescent Kingfisher": {
        "Height (m)": 0.25,
        "Weight (kg)": 0.5,
        "Aggressive": False,
    },
}

for key in rarebirds.keys():
    rarebirds[key]['Seen'] = False
  1. 在 for 循环中使用 rarebirds.keys() 来遍历键。
  2. 你正在做rarebirds[key]['Seen'] == False。双等号正在尝试执行导致keyError 的相等检查。

【讨论】:

  • 谢谢!谢谢!谢谢!这几天我一直在咀嚼它......
  • 迭代一个字典已经给了你密钥,不需要使用dict.keys()。
  • @wjandrea 是的,你是对的。当您明确编写它时,它会更加清晰。
猜你喜欢
  • 2020-05-29
  • 2020-09-13
  • 2019-09-06
  • 1970-01-01
  • 2021-07-25
  • 2019-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多