Getting value of dictionary from list of keys

时间:2019-03-19 14:55:50

标签: python dictionary

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 ?

1 个答案:

答案 0 :(得分: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"