Reputation: 638
I have a problem with python zip and dictionaries. I have list called dirs which contains all directory names. I want to generate something like the below one
dirs_count = {'placements':{'total':0,'Others':0},'x-force':{'total':0,'Others':0})
I used the following code to generate this.
dirs = ['placemetns', 'x-code']
dirs_count = dict(zip(dirs,[{'total':0, 'others': 0}]*len(dirs)))
# {'placements':{'total':0,'others':0},'x-code':{'total':0,'others':0}}
But the problem here is, if I modify one dictionary value, the following thing happens..
dirs_count['placements']['total'] = 5
# {'placements':{'total':5,'others':0},'x-code':{'total':5,'others':0}}
Is there any way to prevent this?
or
Is there any way to generate dirs_count in which it doesn't effect the entier dictionary on modification?
Upvotes: 0
Views: 1916
Reputation: 1044
Use dirs_count = {d: {'total': 0, 'others': 0} for d in dirs}
.
What happens in your case is that both placements
and x-code
refer to the same object.
Upvotes: 3
Reputation: 1603
This is happening because [{'total':0, 'others': 0}]*len(dirs)
gives you a number of references to the same dict, so any changes to one will affect all the copies. try instead
dirs = ['placemetns', 'x-code']
dicts = [{'total':0, 'others': 0} for i in dirs]
dirs_count = dict(zip(dirs,dicts))
Upvotes: 1