Home > Software engineering >  Dictionary update value to every key instead of 1 single key
Dictionary update value to every key instead of 1 single key

Time:12-10

I'm working on a calendar in python. Each key is numbered from 0 to 29 representing days in a month. The calendar dictionary is created as follow (day_available = 30)

calendar = dict.fromkeys(range(day_available), [[], [], [], [], []])

The format of the data being pass in is [day, name, book, return_date]. For example

[['1', 'adam', 'harry potter', '6'], ['17', 'Lauren', 'Eye of the world', '3']]

The purpose of my program is to add the information into the appropriate day. If there is something already in the dictionary for that day, the information will be added in. For example

['1', 'adam', 'harry potter', '6'] 

should be in the dictionary key 1. However, I am having trouble with this loop (info = the example nested list above, data_location = 1)

log_action = list(map(list, zip(*info)))

for index in range(len(log_action)):
    day = int(log_action[row][0])
    data = calendar.get(day)
    information = log_action[row]
    data[data_location].append(information)
    calendar.update({day:data})

I'm confused because when calendar.update({day:data}) runs, instead of updating just the day's (or the key associate with the day) value, it updates every key in the dictionary with that new value.

CodePudding user response:

This fromkeys call assigns the same single list as the value for every key:

calendar = dict.fromkeys(range(day_available), [[], [], [], [], []])

No matter what key you access the dict with, you retrieve (and modify) that same value. It's similar to if you have a bunch of variables all assigned to the same list; any time you modify the list via one variable, all the others "see" the change because they're all pointing to the same object.

To create a dict that has a new list for each key, you could do:

calendar = {k: [[] for _ in range(5)] for k in range(day_available)}

The above dict comprehension evaluates the [[] for _ in range(5)] for each value of k, meaning you get a brand new list assigned as the value to each key.

  • Related