gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:26:17 28 4
gpt4 key购买 nike

我有一个有点复杂的问题,我似乎无法弄清楚。我有一个键列表,对应于 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'] 的值?

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

感谢您的帮助! :)

最佳答案

使用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模块。

关于python - 如何通过遵循键列表更改 python 字典中节点的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19923464/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com