gpt4 book ai didi

python - 如何使用python更新字典中字典的值

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

我有:

new_dict['a1']['Road_Type']=[0,0,0,0,0,0,0]
new_dict['a2']['Road_Type']=[0,0,0,0,0,0,0]
new_dict['a3']['Road_Type']=[0,0,0,0,0,0,0]
new_dict['a4']['Road_Type']=[0,0,0,0,0,0,0]

现在更新后我希望它是:

new_dict['a1']['Road_Type']=[0,0,0,0,0,0,0]
new_dict['a2']['Road_Type']=[5,0,0,0,0,0,0]
new_dict['a3']['Road_Type']=[0,0,0,0,0,0,0]
new_dict['a4']['Road_Type']=[0,0,0,0,0,0,0]

我的代码:

kk=new_dict['a2']['Road_Type']
kk[0]=5
new_dict['a2']['Road_Type']=kk

但结果是:

new_dict['a1']['Road_Type']=[5,0,0,0,0,0,0]
new_dict['a2']['Road_Type']=[5,0,0,0,0,0,0]
new_dict['a3']['Road_Type']=[5,0,0,0,0,0,0]
new_dict['a4']['Road_Type']=[5,0,0,0,0,0,0]

所有值都在更新,那么我如何更新特定值。

最佳答案

根据你对问题的评论,你犯了一个错误,因为你不知道Python是如何工作的。我将在示例中使其变得更简单,但这也代表您拥有 new_dict[a][b]...[n] 时的情况。

以下是您生成字典的方式:

lst = [0, 0, 0, 0, 0, 0, 0]
new_dict = []
for p in range(N):
new_dict[p] = lst

然而,这会将每个 new_dict[p](对于 p=0,...,N)绑定(bind)到相同的 lst,即每个new_dict[p] 值引用 list 的同一实例。

您必须为每个 new_dict[p] 生成新列表。

以下是生成它的方法:

new_dict = {}

for p in range(N):
new_dict[p] = [0, 0, 0, 0, 0, 0, 0]

填充字典后,您可以用一行编辑它:

new_dict['a1']['RoadType'][0] = 5

关于python - 如何使用python更新字典中字典的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48840867/

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