Łukasz
Łukasz

Reputation: 2172

python - nested dictionary as argument

Having following example dictionary:

dict = {
    'key1': {
        'nested_key1': {
            'more_nested_key1': 'a_value'
        }
    },
    'key2': {
        'a_key': 'some_value'
    }
}

I need a function that takes the dict and any number of nested keys and performs an action on the value. For instance:

def replace(dict, '['key1']['nested_key1']['more_nested_key1']', 'new_value')

would replace 'a_value' with 'new_value'. I am new to python, any idea how to achieve that?

Upvotes: 1

Views: 558

Answers (2)

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24133

You can pass a list of keys to the function, iterate through all but the last one of them until you get to the innermost dictionary, and then assign to the final key:

def replace(dict, keys, value):
    d = dict
    for key in keys[:-1]:
        d = d[key]
    d[keys[-1]] = value

Upvotes: 2

FHTMitchell
FHTMitchell

Reputation: 12157

Just iterate through the keys (except for the last), getting the next dict down each time. Then for the final key, set the item in the last dict to value

def replace(dct, *keys, value):
    for key in keys[:-1]:
       dct = dct[key]
    dct[keys[-1]] = value

Usage:

replace(dict, 'key1', 'nested_key1', 'more_nested_key1', value='new_value')

Upvotes: 2

Related Questions