遍历一个嵌套的字典,并将键值为True的实例纳入打印语句中。

问题描述 投票:0回答:1

这是我的字典,其值又是字典本身。

rarebirds = {
    'Golden-crested Toucan' : {
        'Height (m)': 1.1,
        'Weight (kg)': 35,
        'Color':'Gold',
        'Endangered': True,
        'Agressive': True
},
'Pearlescent Kingfisher': {
    'Height (m)': .25,
    'Weight (kg)': .5,
        'Color':'White',
        'Endangered': False,
        'Agressive': False
},
'Four-metre Hummingbird': {
    'Height (m)': .6,
    'Weight (kg)': .5,
    'Color':'Blue',
    'Endangered': True,
    'Agressive': False
},
'Giant Eagle': {
    'Height (m)': 1.5,
    'Weight (kg)': 52,
    'Color':'Black and White',
    'Endangered': True,
    'Agressive': True
},
'Ancient Vulture': {
    'Height (m)': 2.1,
    'Weight (kg)': 70,
    'Color':'Brown',
    'Endangered': False,
    'Agressive': False
}
}

这里是 for 循环不工作。

actions = ['Back Away',
    'Cover our Heads'
    'Take a Photograph']

for i in rarebirds: 
    if (i,'Aggressive')==True:
        print(i+": "+(actions[1]))
    else: print(i+ " is not aggressive")

它输出的是

Golden-crested Toucan is not aggressive
Pearlescent Kingfisher is not aggressive
Four-metre Hummingbird is not aggressive
Giant Eagle is not aggressive
Ancient Vulture is not aggressive

但根据我的字典,巨嘴鸟和老鹰都是攻击性的,所以我想要的是 for 循环来打印我的名为'actions'的列表的index[1]。不知道为什么循环没有成功识别出 True 布尔值。

我到底错在哪里。任何帮助都将是非常感激的。

for-loop nested
1个回答
0
投票

解决了

for i in rarebirds: 
    if rarebirds[i]['Endangered']==True:
        print(i+": "+ (actions[1]))
    else: print(i+ " is not aggressive")
© www.soinside.com 2019 - 2024. All rights reserved.