我不熟悉python中的字典,一直在研究如何迭代和引用嵌套字典中的特定键。例如,在下面的代码中,我希望在字典中只列出每只宠物的名字。现在,我已经列出了每只宠物的所有钥匙
petDict = {
'pet1' : {
'type' : 'dog',
'name' : 'scooby',
'age' : '4'
},
'pet2' : {
'type' : 'cat',
'name' : 'milo',
'age' : '1'
},
'pet3' : {
'type' : 'fish',
'name' : 'danny',
'age' : '2'
}
}
print('Here are my pets:')
for petNum, petInfo in petDict.items():
for key in petInfo:
print(key + ': ', petInfo[key])
电流输出:
type: dog
name: scooby
age: 4
type: cat
name: milo
age: 1
type: fish
name: danny
age: 2
期望输出:
name: scooby
name: milo
name: danny
输出:
您可以简单地使用if条件来检查键是否为
name
,如下所示这样,如果您想获得其他密钥,也可以根据需要的密钥设置附加条件
相关问题 更多 >
编程相关推荐