如何按照键列表更改python字典中节点的值?

如何按照键列表更改python字典中节点的值?,python,list,dictionary,Python,List,Dictionary,我有一个复杂的问题,我似乎无法弄清到底。我有一个对应于Python字典中某个位置的键列表。我希望能够动态更改该位置的值(通过列表中的键找到) 例如: listOfKeys = ['car', 'ford', 'mustang'] 我还有一本字典: DictOfVehiclePrices = {'car': {'ford': {'mustang': 'expensive',

我有一个复杂的问题,我似乎无法弄清到底。我有一个对应于Python字典中某个位置的键列表。我希望能够动态更改该位置的值(通过列表中的键找到)

例如:

listOfKeys = ['car', 'ford', 'mustang']
我还有一本字典:

DictOfVehiclePrices = {'car':
                          {'ford':
                              {'mustang': 'expensive',
                               'other': 'cheap'},
                           'toyota':
                              {'big': 'moderate',
                               'small': 'cheap'}
                          },
                       'truck':
                          {'big': 'expensive',
                           'small': 'moderate'}
                      }
通过我的列表,我如何动态更改
DictOfVehiclePrices['car']['ford']['mustang']

在我的实际问题中,我需要按照字典中的键列表来更改结束位置的值。如何动态地(使用循环等)实现这一点


谢谢你的帮助!:)

一个非常简单的方法是:

DictOfVehiclePrices[listOfKeys[0]][listOfKeys[1]][listOfKeys[2]] = 'new value'
使用和:

更新值:

>>> reduce(getitem, lis[:-1], DictOfVehiclePrices)[lis[-1]] = 'cheap'
获取值:

>>> reduce(getitem, lis, DictOfVehiclePrices)
'cheap'

请注意,在Python 3中,reduce已移动到模块

输出

expensive
{'car': {'toyota': {'small': 'cheap', 'big': 'moderate'},
 'ford': {'mustang': 'cheap', 'other': 'cheap'}},
 'truck': {'small': 'moderate', 'big': 'expensive'}}
为了更改值

result = dictOfVehiclePrices
for key in listOfKeys[:-1]:
    result = result[key]

result[listOfKeys[-1]] = "cheap"
print dictOfVehiclePrices
输出

expensive
{'car': {'toyota': {'small': 'cheap', 'big': 'moderate'},
 'ford': {'mustang': 'cheap', 'other': 'cheap'}},
 'truck': {'small': 'moderate', 'big': 'expensive'}}
你有一个伟大的解决方案@Joel Cornett

基于Joel方法,您可以这样使用它:

def set_value(dict_nested, address_list):
    cur = dict_nested
    for path_item in address_list[:-2]:
        try:
            cur = cur[path_item]
        except KeyError:
            cur = cur[path_item] = {}
    cur[address_list[-2]] = address_list[-1]

DictOfVehiclePrices = {'car':
                      {'ford':
                          {'mustang': 'expensive',
                           'other': 'cheap'},
                       'toyota':
                          {'big': 'moderate',
                           'small': 'cheap'}
                      },
                   'truck':
                      {'big': 'expensive',
                       'small': 'moderate'}
                  }

set_value(DictOfVehiclePrices,['car', 'ford', 'mustang', 'a'])

print DictOfVehiclePrices
  • STDOUT:
{'car':{'toyota':{'small':'便宜','大':'中等'},'福特': {‘野马’:‘a’,‘其他’:‘便宜’}},‘卡车’:{‘小’:‘中等’, “大”:“贵”}

下面是一个递归函数,用于根据键列表更新嵌套dict:

1.使用所需参数触发update dict函数

2.函数将迭代键列表,并从dict中检索值

3.如果检索到的值是dict,它将从列表中弹出该键,并使用该键的值更新dict

4.将更新的dict和密钥列表递归发送到同一函数


5.当列表为空时,表示我们已达到所需的密钥,需要在其中应用替换。因此,如果列表为空,函数将用值替换dict[key]

这将允许您检索该值,但提问者希望能够修改它。抱歉,如果我在这个问题中遗漏了显而易见的内容,那么“getitem”是什么?我不太明白…@user2590203
来自operator import getitem
好的对不起!我错过了…:/这将允许您检索值,但提问者希望能够修改它。它不允许更改值,它只是一个查找。很好,但您可能希望对列表进行切片,以便获得第一个值,并在最终值上使用
setitem
或其他内容。
def update_dict(parent, data, value):
    '''
    To update the value in the data if the data
    is a nested dictionary
    :param parent: list of parents
    :param data: data dict in which value to be updated
    :param value: Value to be updated in data dict
    :return:
    '''
    if parent:
        if isinstance(data[parent[0]], dict):
            update_dict(parent[1:], data[parent[0]], value)
        else:
            data[parent[0]] = value


parent = ["test", "address", "area", "street", "locality", "country"]
data = {
    "first_name": "ttcLoReSaa",
    "test": {
        "address": {
            "area": {
                "street": {
                    "locality": {
                        "country": "india"
                    }
                }
            }
        }
    }
}
update_dict(parent, data, "IN")