Sudhanshu Bhandarwar
Sudhanshu Bhandarwar

Reputation: 11

how to update the value of dictionary in a dictionary using python

I have:

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]

Now after updating I want it to be:

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]

My code:

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

but the result is:

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]

all value are getting updated, so how can I update particular value.

Upvotes: 1

Views: 77

Answers (3)

Usman
Usman

Reputation: 2029

Try this code : There is a small mistake in your code ,you update the index 0 of 'a2' and then assign the 'kk' that point the new_dict of 'a2'

Program :

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)

Output :

{'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]}}

Upvotes: 0

Ilija
Ilija

Reputation: 1604

Based on your comments on your question, you are making a mistake due to not knowing how Python works. I'll make it simpler in example, but this also stands for your case when you have new_dict[a][b]...[n].

Here is how you probably are generating your dictionary:

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

This however binds every new_dict[p], for p=0,...,N to the same lst, i.e. each new_dict[p] value references the same instance of list.

You have to generate new list for each new_dict[p].

Here is how you should generate it:

new_dict = {}

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

After your dictionary is populated, you can edit it with one line:

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

Upvotes: 1

RoadRunner
RoadRunner

Reputation: 26315

Just update a2 separately:

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)

Output:

{'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]}}

Upvotes: 0

Related Questions