简体   繁体   中英

Access and modify Python dict with *args variable

I would like to access a nested dict in a function using *args as a sort of key path.

How would this be achieved? Can I create an inline for loop to dynamically generate the dict accesses?

I'd like to do as follows:

def modify_dict(mydict, *keypath):
    if mydict[keypath[0]][keypath[1]][keypath[2]]... == "This will be changed":
        mydict[keypath[0]][keypath[1]][keypath[2]]... = "New Value"


d = {"key1": {"key2": {"key3": "This will be changed"}}}

# d["key1"]["key2"]["key3"] should become "New Value"
modify_dict(d, "key1", "key2", "key3")

I thought of doing a loop ie

_mydict = mydict
for i in range(len(keypath) - 1):
    _mydict = _mydict[keypath[i]]

which could access the value at the keypath, but then, how would I do modifications?

I am not entirely sure why you'd want to do this, but you can achieve it using iterators -

d = {"key1": {"key2": {"key3": "This will be changed"}}}
def modify_dict(d, val, *args):
    inner_dict = d
    iter_d = iter(args)
    while True:
        try:
            k = next(iter_d)
            if isinstance(inner_dict[k], dict):
                inner_dict = inner_dict[k]
        except StopIteration:
            inner_dict[k] = val
            break

modify_dict(d, "new_value", "key1", "key2", "key3")
print(d)

Output

{'key1': {'key2': {'key3': 'new_value'}}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM