我有以下字典,其中包含嵌套字典:
rarebirds = {
'Gold-crested Toucan': {
'Height (m)': 1.1,
'Weight (kg)': 35,
'Color': 'Gold',
'Endangered': True,
'Aggressive': True},
'Pearlescent Kingfisher': {
'Height (m)': 0.25,
'Weight (kg)' : 0.5,
'Color': 'White',
'Endangered': False,
'Aggressive': False},
'Four-metre Hummingbird': {
'Height (m)': 0.6,
'Weight (kg)': 0.5,
'Color' : 'Blue',
'Endangered' : True,
'Aggressive' : False},
'Giant Eagle': {
'Height (m)' : 1.5,
'Weight (kg)' : 52,
'Color' : 'Black and White',
'Endangered' : True,
'Aggressive' : True},
'Ancient Vulture': {
'Height (m)' : 2.1,
'Weight (kg)' : 70,
'Color' : 'Brown',
'Endangered' : False,
'Aggressive': False}
}
如果此列表中的鸟确实具有攻击性,我应该打印出“Cover your head”的声明。我不知道如何让 Python 遍历列表中的每个元素并仅在鸟具有攻击性时才打印某些内容。请指教。
答案 0 :(得分:0)
试试这个,它遍历字典值:
rarebirds = {...}
for bird_dict in rarebirds.values():
if bird_dict["aggressive"]:
print("Cover your head!")
或者,您可以遍历字典的键:
rarebirds = {...}
for bird in rarebirds:
if rarebirds[bird]["aggressive"]:
print("Cover your head!")
两种方式都行;这主要取决于您的喜好。