Search code examples
pythondictionarykey

Getting list of sub-keys for a given key


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]


Solution

  • 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: []