我有:
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]
所有值都在更新,因此如何更新特定值。
答案 0 :(得分:0)
只需单独更新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]}}
答案 1 :(得分: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
绑定到相同的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
答案 2 :(得分: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]}}