繁体   English   中英

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

[英]how to update the value of dictionary in a dictionary using python

我有:

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]每个new_dict[p]绑定到相同的lst ,因为p=0,...,N ,即每个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

只需单独更新a2

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

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

print(new_dict)

输出:

{'a1': {'Road_Type': [0, 0, 0, 0, 0, 0, 0]}, 
 'a2': {'Road_Type': [5, 0, 0, 0, 0, 0, 0]}, 
 'a3': {'Road_Type': [0, 0, 0, 0, 0, 0, 0]}, 
 'a4': {'Road_Type': [0, 0, 0, 0, 0, 0, 0]}}

试试这个代码:你的代码有一个小错误,你更新'a2'的索引0,然后分配指向'a2'的new_dict的'kk'

程序 :

new_dict = {}
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]}


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

print(new_dict)

输出 :

{'a2': {'Road_Type': [5, 0, 0, 0, 0, 0, 0]}, 
 'a3': {'Road_Type': [0, 0, 0, 0, 0, 0, 0]},
 'a4': {'Road_Type': [0, 0, 0, 0, 0, 0, 0]},
 'a1': {'Road_Type': [0, 0, 0, 0, 0, 0, 0]}}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM