Wasim Karani
Wasim Karani

Reputation: 8886

Basic Dict manipulation in python

I have a python dict,

D = {
    'outermost': {
        'inner': {
            'key1': '', 
            'key2': '', 
            'key3': '', 
            'key4': '', 
            'key5': ''
        }
    }
}

a list,

L = ['outermost', 'inner']

and a string,

K = 'key1'

and a value,

V = 'add a value'

How can I get a output like this

D = {
    'outermost': {
        'inner': {
            'key1': 'add a value', 
            'key2': '', 
            'key3': '', 
            'key4': '', 
            'key5': ''
        }
    }
}

Upvotes: 2

Views: 124

Answers (2)

Joel Cornett
Joel Cornett

Reputation: 24788

Like this:

# Will raise a KeyError if the path does not exist.
def set_dict_path(dct, path, key, value):
    for p in path:
        dct = dct[p]

    dct[key] = value

set_dict_path(D, L, K, V)

Upvotes: 1

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250931

Using reduce and operator.getitem:

from operator import getitem
reduce(getitem, L, D)[K] = V

Output:

>>> from pprint import pprint
>>> pprint(D)
{'outermost': {'inner': {'key1': 'add a value',
                         'key2': '',
                         'key3': '',
                         'key4': '',
                         'key5': ''}}}

Upvotes: 5

Related Questions