user3266890
user3266890

Reputation: 555

How to change one dictionary value in a dictionary of dictionaries

I am running a variation of the following script:

text1={'file1':0,'file2':0}
text2=['100-200','200-300','300-400']
text3=['1','2','3','4']
level1={}
level2={}
for i in text2:
    level1[i]=text1
for n in text3:
    level2[n]=level1
level2['3']['100-200']['file1']=level2['3']['100-200']['file1']+1

Unfortunately this changes the dictionary from:

{'1': {'200-300': {'file2': 0, 'file1': 0}, '300-400': {'file2': 0, 'file1': 0}, '100-200': {'file2': 0, 'file1': 0}}, '2': {'200-300': {'file2': 0, 'file1': 0}, '300-400': {'file2': 0, 'file1': 0}, '100-200': {'file2': 0, 'file1': 0}}, '3': {'200-300': {'file2': 0, 'file1': 0}, '300-400': {'file2': 0, 'file1': 0}, '100-200': {'file2': 0, 'file1': 0}}, '4': {'200-300': {'file2': 0, 'file1': 0}, '300-400': {'file2': 0, 'file1': 0}, '100-200': {'file2': 0, 'file1': 0}}}

to:

{'1': {'200-300': {'file2': 0, 'file1': 1}, '300-400': {'file2': 0, 'file1': 1}, '100-200': {'file2': 0, 'file1': 1}}, '2': {'200-300': {'file2': 0, 'file1': 1}, '300-400': {'file2': 0, 'file1': 1}, '100-200': {'file2': 0, 'file1': 1}}, '3': {'200-300': {'file2': 0, 'file1': 1}, '300-400': {'file2': 0, 'file1': 1}, '100-200': {'file2': 0, 'file1': 1}}, '4': {'200-300': {'file2': 0, 'file1': 1}, '300-400': {'file2': 0, 'file1': 1}, '100-200': {'file2': 0, 'file1': 1}}}

How do I change only one of the file values and not all of them?

Upvotes: 0

Views: 70

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121942

Use a dict comprehension to produce your structure, where loop expressions are evaluated each iteration:

level2 = {n: {i: {'file1':0,'file2':0} for i in text2}} for n in text3}

You are not creating copies of the dictionaries, merely storing references to one dictionary object.

Thus, each time you stored text1 you created a reference, not a copy, and the same goes for each time you referenced level1.

Upvotes: 1

Related Questions