Achmn
Achmn

Reputation: 25

Update an element of a list, where list is a value in dictionary

When I'm trying to update an element of a list, where list is a value in dictionary, it updates all values at that index in every list in the dictionary.

Sample code:

dit = {}
d = {}
ls = ['hhh','ew']
a = "hhh"
b = "ew"
j = 3
dit[a] = [1,2,3,4]
dit[b] = [5,6,7,8]
const = [0,2,3,4]
d = dict.fromkeys(dit.keys() ,const)
print(d)
for i in ls:
    print(i)
    d[i][0] = max(d[i][0], j) 
    print(d)
    j += 1

OUTPUT I'm getting is:

{'hhh': [0, 2, 3, 4], 'ew': [0, 2, 3, 4]}
hhh
{'hhh': [3, 2, 3, 4], 'ew': [3, 2, 3, 4]}
ew
{'hhh': [4, 2, 3, 4], 'ew': [4, 2, 3, 4]}

Output required is:

{'hhh': [0, 2, 3, 4], 'ew': [0, 2, 3, 4]}
hhh
{'hhh': [3, 2, 3, 4], 'ew': [0, 2, 3, 4]}
ew
{'hhh': [3, 2, 3, 4], 'ew': [4, 2, 3, 4]}

Upvotes: 0

Views: 83

Answers (1)

IoaTzimas
IoaTzimas

Reputation: 10624

This happens because you assign the const itself on each dict element. When you update this list, it will update all of its occurences. Change this in your code and it will work:

d = dict.fromkeys(dit.keys() ,const)

to

d = {i:const.copy() for i in dit.keys()}

Upvotes: 1

Related Questions