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?
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With