Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dictionary update value to every key instead of 1 single key

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

['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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading