0

I am trying to update the value for a particular key in a dictionary. However, for some reason, all the keys in the dictionary are updated with that value. I don't know what part of the code throws out this issue.

Below is the code

# get unique values to use as keys
array = list(assignments.values())
new_key = list(set([x for l in array for x in l]))
print('key list is {}'.format(new_key) + '\n')

# initiate a dictionary with empty lists as values
d=dict.fromkeys(new_key,[])
print('empty dictionary is {}'.format(d) + '\n')

# add values of 'Monday' to new dictionary key of Jen
d['Jeh'].append('Monday')

print(d)

Here's the output from the code block above  -- as you can see in the last line of the output, instead of having 'Monday' as the value for 'Jeh' key only, all other keys are also updated with 'Monday'. 

key list is ['Ben', 'Chinmay', 'Samuel', 'Michael', 'Shishir', 'Jeh', 'Rachel', 'Evan', 'Yandi', 'Raghav']

empty dictionary is {'Ben': [], 'Chinmay': [], 'Samuel': [], 'Michael': [], 'Shishir': [], 'Jeh': [], 'Rachel': [], 'Evan': [], 'Yandi': [], 'Raghav': []}

{'Ben': ['Monday'], 'Chinmay': ['Monday'], 'Samuel': ['Monday'], 'Michael': ['Monday'], 'Shishir': ['Monday'], 'Jeh': ['Monday'], 'Rachel': ['Monday'], 'Evan': ['Monday'], 'Yandi': ['Monday'], 'Raghav': ['Monday']}
  • I think that when you use `dict.fromkeys` it assigns the same list to all the keys. Because list is a reference type, all the keys would refer to the same list (the same memory location). Hence, updating one key updates all of them. – SagiZiv Jan 15 '22 at 18:56
  • Try to initialize the dict woth a for-loop, and it would probably solve it – SagiZiv Jan 15 '22 at 18:58
  • 1
    @SagiZiv **everything** is a "reference type" in Python. But yes, this is the issue. OP, use `{k: [] for k in new_key}` – juanpa.arrivillaga Jan 15 '22 at 18:59
  • 1
    @juanpa.arrivillaga thank you!! – daisynorthwest Jan 16 '22 at 14:25

0 Answers0