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

后端 未结 8 883
忘了有多久
忘了有多久 2020-12-01 09:36

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 i

8条回答
  •  甜味超标
    2020-12-01 09:38

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

提交回复
热议问题