Getting list of sub-keys for a given key

42 Views Asked by At

How do I create a function to get a list of all the subkeys within a dictionary for a given key.

Data = {
            'Andrew': {
                'Country': 'Australia',
                'Age': '20',
                
          
            },
            'Mary': {
                'Country': 'Australia',
                'Age': '25',
                'Gender': 'Female',
                
            },
  }

For a given key e.g Andrew or Mary I'd like to know the keys present. So if I ask for Andrew: It gives [Country, Age] and Mary is [Country,Age,Gender]

2

There are 2 best solutions below

1
tousif Noor On BEST ANSWER

As you want to do via function. here you can make something like this

def get_subkeys(dictionary, key):
    if key in dictionary:
        return list(dictionary[key].keys())
    else:
        return []

USAGE:

data = {
    'Andrew': {
        'Country': 'Australia',
        'Age': '20',
    },
    'Mary': {
        'Country': 'Australia',
        'Age': '25',
        'Gender': 'Female',
    },
}

print(get_subkeys(data, 'Andrew'))  # Output: ['Country', 'Age']
print(get_subkeys(data, 'Mary'))    # Output: ['Country', 'Age', 'Gender']
print(get_subkeys(data, 'John'))    # Output: []
1
Jean-Baptiste Quenot On

Barmar has the right answer:

>>> list(Data['Andrew'].keys())
['Country', 'Age']
>>> list(Data['Mary'].keys())
['Country', 'Age', 'Gender']