Search code examples
pythonlistdictionary

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


I'm trying 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?

Python


Solution

  • 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'}}}