Python - FOR loop not writing correct values in nested dictionaries -


hopefully can me none of research has helped me. have simple dictionary:

mydict = {     1: {1: 'foo'},     2: {1: 'bar'}     } 

i'm duplicating each of key / value pairs assigning new key values:

nextkey = len(mydict) + 1 currkey in range(len(mydict)):     mydict[nextkey] = mydict[currkey + 1]     nextkey += 1 

which give me mydict of:

{     1: {1: 'foo'},     2: {1: 'bar'},     3: {1: 'foo'},     4: {1: 'bar'},     } 

i want add new key value pair of existing nested dictionaries. keys each should '2' , values each should increase each nested dictionary:

newvalue = 1 key in mydict:     mydict[key][2] = newvalue     newvalue += 1 

i expecting:

{     1: {1: 'foo', 2: 1},     2: {1: 'bar', 2: 2},     3: {1: 'foo', 2: 3},     4: {1: 'bar', 2: 4},     } 

but giving me mydict of:

{     1: {1: 'foo', 2: 3},     2: {1: 'bar', 2: 4},     3: {1: 'foo', 2: 3},     4: {1: 'bar', 2: 4},     } 

i have used visualisation tool of ide i'm using , after have run loop duplicate key / value pairs appears new keys reference duplicated value rather containing it, perhaps has it?

ide visualisation

can please / explain?

this happens because in first loop not copying nested dictionaries rather adding new reference same dictionaries.

to maybe give clearer example: if break out of second loop after 2 loops (with original code) output be:

{1: {1: 'foo', 2: 1},  2: {1: 'bar', 2: 2},  3: {1: 'foo', 2: 1},  4: {1: 'bar', 2: 2}} 

so can fix first loop this:

for currkey in range(len(mydict)):     mydict[nextkey] = mydict[currkey + 1].copy()     nextkey += 1 

the copy() function creates real copy of dictionary can access these 4 different dictionaries in second loop.


Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -