access nested set with array params python 1

access nested set with array params python

def nested_set(dic, keys, value):
    for key in keys[:-1]:
        dic = dic.setdefault(key, {})
    dic[keys[-1]] = value
    
>>> d = {}
>>> nested_set(d, ['person', 'address', 'city'], 'New York')
>>> d
{'person': {'address': {'city': 'New York'}}}

from : 
https://stackoverflow.com/questions/13687924/setting-a-value-in-a-nested-python-dictionary-given-a-list-of-indices-and-value

Here is what the above code is Doing:
1. It takes a dictionary, a list of keys, and a value.
2. It iterates over the keys except the last one.
3. For each key, it gets the value of the key in the dictionary. If the key doesn’t exist, it creates a new dictionary.
4. It sets the last key to the value.

Similar Posts