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

2024-09-30 20:16:47 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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


Tags: falsetruefor字典asheightweightkg
1条回答
网友
1楼 · 发布于 2024-09-30 20:16:47
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。double equals正在尝试执行相等检查,这导致keyError

相关问题 更多 >