0

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.

mapgeek
  • 13
  • 2
  • Does this answer your question? [Python initializing a list of lists](https://stackoverflow.com/questions/12791501/python-initializing-a-list-of-lists) In your case it is a list of empty dicts but the situation is essentially the same. In short, you can try `[{} for _ in day_list]` – j1-lee Oct 15 '21 at 21:33
  • Valuable education: [Python Names and Values](https://nedbatchelder.com/text/names1.html) – jarmod Oct 15 '21 at 21:40
  • It looks like the `*` operator was the issue. It created a list of not just the same values, but the same object. So updating any one of them was updating all of them. Creating `days` like this works the way I expected: `days = dict(zip(day_list, [{} for i in range(len(day_list)+1)]))` – mapgeek Oct 15 '21 at 22:02
  • Test for the object's reuse with the `id()` function. – mapgeek Oct 15 '21 at 22:04

0 Answers0