如何将带有键的字典元素设置为数组?
How to set dictionary element with key as array?
如果我想使用数组从字典中获取值,我会这样做:
def get_dict_with_arr(d, arr):
accumulator = d
for elem in arr:
accumulator = accumulator[elem]
return accumulator
并像这样使用它:
test_dict = {
'this': {
'is': {
'it': 'test'
}
}
}
get_dict_with_arr(test_dict, ['this', 'is', 'it']) # returns 'test'
我的问题是,如何编写一个设置值而不是获取值的函数?基本上我想写一个set_dict_with_arr(d, arr, value)
函数。
尝试:
def set_dict_with_arr(d, arr, value):
cur_d = d
for v in arr[:-1]:
cur_d.setdefault(v, {})
cur_d = cur_d[v]
cur_d[arr[-1]] = value
return d
test_dict = {"this": {"is": {"it": "test"}}}
test_dict = set_dict_with_arr(test_dict, ["this", "is", "it"], "new value")
print(test_dict)
打印:
{"this": {"is": {"it": "new value"}}}
如果我想使用数组从字典中获取值,我会这样做:
def get_dict_with_arr(d, arr):
accumulator = d
for elem in arr:
accumulator = accumulator[elem]
return accumulator
并像这样使用它:
test_dict = {
'this': {
'is': {
'it': 'test'
}
}
}
get_dict_with_arr(test_dict, ['this', 'is', 'it']) # returns 'test'
我的问题是,如何编写一个设置值而不是获取值的函数?基本上我想写一个set_dict_with_arr(d, arr, value)
函数。
尝试:
def set_dict_with_arr(d, arr, value):
cur_d = d
for v in arr[:-1]:
cur_d.setdefault(v, {})
cur_d = cur_d[v]
cur_d[arr[-1]] = value
return d
test_dict = {"this": {"is": {"it": "test"}}}
test_dict = set_dict_with_arr(test_dict, ["this", "is", "it"], "new value")
print(test_dict)
打印:
{"this": {"is": {"it": "new value"}}}