Search code examples
pythonpython-3.xnestedsquare

How do I access values in a complex nested multi value python dictonary


  • I have a dictionary format below. It is a single line, but I formatted it here. Notice the nested Key "SshPublicKeys" that has itself a nested key-value group in square brackets.
{
    'ServerId': 'string',
    'User': {
        'HomeDirectory': 'string',
        'SshPublicKeys': [
            {
                'DateImported': datetime(2015, 1, 1),
                'SshPublicKeyId': '123'
            },
                        {
                'DateImported': datetime(2018, 1, 1),
                'SshPublicKeyId': '456'
            },
        ],
        'UserName': 'string'
    }
}
  • In this format, how do I access all the "SshPublicKeyId" key-value pairs? The final output should look like the below or just close to it.
'SshPublicKeyId': '123' 
'SshPublicKeyId': '456'

Solution

  • for public_key in dicta["User"]["SshPublicKeys"]:
        print(f"'SshPublicKeyId': '{public_key['SshPublicKeyId']}'")
    

    Output:

    'SshPublicKeyId': '123'
    'SshPublicKeyId': '456'