Python 使用for循环将项添加到嵌套字典
我正在尝试使用for循环在嵌套字典中添加项。该项目应该在内部字典中,因此它显示为项目Python 使用for循环将项添加到嵌套字典,python,python-3.x,dictionary,nested,Python,Python 3.x,Dictionary,Nested,我正在尝试使用for循环在嵌套字典中添加项。该项目应该在内部字典中,因此它显示为项目“侵略性”:True之后的项目,并且在每个内部字典中,即“金冠巨嘴鸟”和“珠光翠鸟” rarebirds = { 'Gold-crested Toucan': { 'Height (m)': 1.1, 'Weight (kg)': 35, 'Aggressive': True}, 'Pearlescent Kingfisher': {
“侵略性”:True
之后的项目,并且在每个内部字典中,即“金冠巨嘴鸟”
和“珠光翠鸟”
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'
对于这个简单问题的建议将不胜感激
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
rarebirds.keys()
rarebirds[key]['Seen']==False
。双等于正在尝试执行相等检查,这会导致键错误
非常感谢。非常感谢。非常感谢。我已经琢磨了好几天了……迭代一个dict已经给你钥匙了,不需要使用
dict.keys()
@wjandrea是的,你是对的。当您显式编写它时,它会更加清晰。欢迎使用堆栈溢出!查看和。我投票决定结束这个问题,因为它最终是一个打字错误,=
vs=
,但别担心,它会发生在每个人身上:)