python中的基本Dict操作

时间:2014-01-10 15:55:00

标签: python dictionary

我有一个python dict,

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

列表,

L = ['outermost', 'inner']

和一个字符串,

K = 'key1'

和一个值,

V = 'add a value'

如何获得输出,就像这样

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

2 个答案:

答案 0 :(得分:5)

使用reduceoperator.getitem

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

<强>输出:

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

答案 1 :(得分:1)

像这样:

# 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)