Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用for循环将项添加到嵌套字典_Python_Python 3.x_Dictionary_Nested - Fatal编程技术网

Python 使用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': {

我正在尝试使用for循环在嵌套字典中添加项。该项目应该在内部字典中,因此它显示为项目
“侵略性”: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
  • 在for循环中使用
    rarebirds.keys()
  • 您正在执行
    rarebirds[key]['Seen']==False
    。双等于正在尝试执行相等检查,这会导致
    键错误

  • 非常感谢。非常感谢。非常感谢。我已经琢磨了好几天了……迭代一个dict已经给你钥匙了,不需要使用
    dict.keys()
    @wjandrea是的,你是对的。当您显式编写它时,它会更加清晰。欢迎使用堆栈溢出!查看和。我投票决定结束这个问题,因为它最终是一个打字错误,
    =
    vs
    =
    ,但别担心,它会发生在每个人身上:)