I have a list that I want to be the keys of a dict. I am trying to initialize all the dict's values to an empty dict using zip, like this:
day_list = list(range(1,4))
days = dict(zip(day_list, [{}] * len(day_list)))
The days
dict initially looks like what I want, but the problem appears once I start trying to populate it.
for day, day_dict in days.items():
print('Processing day', day)
day_dict['input_file'] = 'forecast_day{}.zip'.format(day)
print(days)
All the values are from the last time through the for
loop. It seems like the values in my dict are all pointing to the same object, since they all contain the last settings of the loop:
Processing day 1
Processing day 2
Processing day 3
{1: {'input_file': 'forecast_day3.zip'}, 2: {'input_file': 'forecast_day3.zip'}, 3: {'input_file': 'forecast_day3.zip'}}
If I create days
like this (instead of via zip
), everything works like I'd expect, in that the values can all be set independently:
days = {}
for day in day_list:
days[day] = {}
While that solves my problem, it doesn't further my understanding. It also feels less Pythonic than zipping two lists. Any wisdom on understanding why my first attempt didn't work and/or how to do this in a Pythonic way is greatly appreciated.