如何使用python中的嵌套字典选择特定键?

2024-09-30 14:27:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我不熟悉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

Tags: keyname宠物age字典typecatprint
2条回答
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():
    print('name: ', petInfo["name"])

输出:

Here are my pets:
name:  scooby
name:  milo
name:  danny

您可以简单地使用if条件来检查键是否为name,如下所示

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:
        if key == 'name':
            print(key + ': ', petInfo[key])

这样,如果您想获得其他密钥,也可以根据需要的密钥设置附加条件

相关问题 更多 >