peterk peterk - 1 year ago 72
Python Question

Setting a value in a nested python dictionary given a list of indices and value

Sorry if this question has been answered before - I've been searching for solutions but I maybe am not using the correct search terms.

Anyway, what I'm trying to do is to programmatically set a value in a dictionary, potentially nested, given a list of indices and a value.

So for example, let's say my list of indices is:

['person', 'address', 'city']

and the value is

'New York'

I want as a result a dictionary object like:

{ 'Person': { 'address': { 'city': 'New York' } }

Basically, the list represents a 'path' into a nested dictionary.

I think I can construct the dictionary itself, but where I'm stumbling is how to set the value. Obviously if I was just writing code for this manually it would be:

dict['Person']['address']['city'] = 'New York'

But how do I index into the dictionary and set the value like that programmatically if I just have a list of the indices and the value?

Hope this makes sense and isn't too dumb a question... :) Thanks for any help.

Answer Source

Something like this could help:

def nested_set(dic, keys, value):
    for key in keys[:-1]:
        dic = dic.setdefault(key, {})
    dic[keys[-1]] = value

And you can use it like this:

>>> d = {}
>>> nested_set(d, ['person', 'address', 'city'], 'New York')
>>> d
{'person': {'address': {'city': 'New York'}}}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download