0

I need to access an element from dictionary by using list of keys.

Dictionary,

groups ={
    'servers': {
        'unix_servers': {
            'server_a': '10.0.0.1',
            'server_b': '10.0.0.2',
            'server_group': {
                'server_e': '10.0.0.5',
                'server_f': '10.0.0.6'
            }
        },
        'windows_servers': {
            'server_c': '10.0.0.3',
            'server_d': '10.0.0.4'
        }
    }
}

Here I want to access key 'server_e' by using the list of keys,

keys = ['servers', 'unix_servers', 'server_group', 'server_e']

These keys are in order but I dont know beforehand what keys are in this list.

So how can I access 'server_e' value i.e. '10.0.0.5' by using this list of keys ?

Shoyeb Sheikh
  • 2,659
  • 2
  • 10
  • 19

1 Answers1

3

This can be done like this, replacing the dict you are querying as you move down the list of keys:

d = groups 
for key in keys:
    d = d[key]

print(d)

If you want to be able to change the end value you can store a reference to the next-to-last element:

d = groups 
p = None
for key in keys:
    p = d
    d = d[key]

p[key] = "new value here"
Christian Sloper
  • 7,440
  • 3
  • 15
  • 28