使用for循环将项目添加到嵌套字典

时间:2020-02-09 18:52:40

标签: python python-3.x dictionary nested

我正在尝试使用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'

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

1 个答案:

答案 0 :(得分:0)

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