问题描述
对不起,如果这个问题已经得到回答,我一直在寻找解决方案,但我可能没有使用正确的搜索字词。
Sorry if this question has been answered before - I've been searching for solutions but I maybe am not using the correct search terms.
无论如何,尝试做的是以编程方式设置字典中的值,可能嵌套,给出索引列表和值。
Anyway, what I'm trying to do is to programmatically set a value in a dictionary, potentially nested, given a list of indices and a value.
所以例如,我的列表索引是:
So for example, let's say my list of indices is:
['person', 'address', 'city']
,值为
'New York'
我想要一个字典对象,如:
I want as a result a dictionary object like:
{ 'Person': { 'address': { 'city': 'New York' } }
基本上,列表表示嵌套字典中的路径。
Basically, the list represents a 'path' into a nested dictionary.
我认为我可以构建字典本身,但是我绊倒的是如何设置值。显然,如果我只是手动编写代码,那将是:
I think I can construct the dictionary itself, but where I'm stumbling is how to set the value. Obviously if I was just writing code for this manually it would be:
dict['Person']['address']['city'] = 'New York'
但是,如何索引到字典并设置值像编程方式,如果我只是有一个索引和值的列表?
But how do I index into the dictionary and set the value like that programmatically if I just have a list of the indices and the value?
希望这是有道理的,不是太笨的问题... :)谢谢你任何帮助。
Hope this makes sense and isn't too dumb a question... :) Thanks for any help.
推荐答案
这样的事情可以帮助:
def nested_set(dic, keys, value):
for key in keys[:-1]:
dic = dic.setdefault(key, {})
dic[keys[-1]] = value
你可以这样使用: p>
And you can use it like this:
>>> d = {}
>>> nested_set(d, ['person', 'address', 'city'], 'New York')
>>> d
{'person': {'address': {'city': 'New York'}}}
这篇关于在嵌套的python字典中设置一个值,给出索引和值的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!