Home > Software engineering >  How do I select a specific key with nested dictionaries in python?
How do I select a specific key with nested dictionaries in python?

Time:09-29

I'm new to working with dictionaries in python and have been stuck on how I can iterate through and reference a specific key within a nested dictionary. For instance, in the following code, I'm looking to list out only the pet names for each pet in the dictionary. Right now, I have all of the keys in each pet being listed out.

    '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])

current output:

type:  dog
name:  scooby
age:  4
type:  cat
name:  milo
age:  1
type:  fish
name:  danny
age:  2

desired output:

name: scooby
name: milo
name: danny

CodePudding user response:

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"])

output :

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

CodePudding user response:

You can simply have an if condition to check whether the key is name like below.

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])

In this way if you want to get other keys also you can put additional conditions according to the key needed.

  • Related