Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating dictionary in Python by key changing other keys [duplicate]

I want to create a dictionary using two lists as keys

regions = ['A','B','C','D']
subregions = ['north', 'south']
region_dict = dict.fromkeys(regions, dict.fromkeys(subregions))

this produces the dictionay I want correctly:

{'A': {'north': None, 'south': None},
 'B': {'north': None, 'south': None},
 'C': {'north': None, 'south': None},
 'D': {'north': None, 'south': None}}

However, if I try to update one of elements in this dict, I see that other elements are also being updated

region_dict['A']['north']=1
>>> {'A': {'north': 1, 'south': None},
     'B': {'north': 1, 'south': None},
     'C': {'north': 1, 'south': None},
     'D': {'north': 1, 'south': None}}

I am not sure what exactly I'm doing wrong here. How can I update just one of the values in this dictionary?

like image 817
igrolvr Avatar asked Oct 18 '25 19:10

igrolvr


1 Answers

You can't use dict.fromkeys when the value to use with each key is mutable; it uses aliases of the same value as the value for every key, so you get the same value no matter which key you look up. It's basically the same problem that occurs with multiplying lists of lists. A simple solution is to replace the outer dict.fromkeys with a dict comprehension:

region_dict = {region: dict.fromkeys(subregions) for region in regions}
like image 117
ShadowRanger Avatar answered Oct 21 '25 08:10

ShadowRanger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!