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

时间:2013-11-12 07:39:05

标签: python list dictionary

我有一个复杂的问题,我似乎无法深究。我有一个与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']

的值

在我的实际问题中,我需要通过字典按键列表并更改结束位置的值。如何动态完成(使用循环等)?

感谢您的帮助! :)

4 个答案:

答案 0 :(得分:4)

使用reduceoperator.getitem

>>> from operator import getitem
>>> lis = ['car', 'ford', 'mustang']

更新价值:

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

获取值:

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

请注意,在Python 3中,reduce已移至functools模块。

答案 1 :(得分:1)

一种非常简单的方法是:

DictOfVehiclePrices[listOfKeys[0]][listOfKeys[1]][listOfKeys[2]] = 'new value'

答案 2 :(得分:1)

print reduce(lambda x, y: x[y], listOfKeys, dictOfVehiclePrices)

<强>输出

expensive

为了更改值,

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

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

<强>输出

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

答案 3 :(得分:-1)

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

这是一个递归函数,用于根据键列表更新嵌套字典:

1。使用必需的参数触发update dict函数

2。该函数将迭代键列表,并从字典中检索值。

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

4。将更新的字典和键列表递归发送到同一函数。

5。当列表为空时,表示我们已达到所需的密钥,需要在此处应用替换。因此,如果列表为空,则该功能将dict [key]替换为值

相关问题