Skip to content Skip to sidebar Skip to footer

Python - Updating Value In One Dictionary Is Updating Value In All Dictionaries

I have a list of dictionaries called lod. All dictionaries have the same keys but different values. I am trying to update one specific value in the list of values for the same key

Solution 1:

The problem is in how you created the list of dictionaries. You probably did something like this:

list_of_dicts = [{}] * 20

That's actually the same dict 20 times. Try doing something like this:

list_of_dicts = [{} for _ in range(20)]

Without seeing how you actually created it, this is only an example solution to an example problem.

To know for sure, print this:

[id(x) for x in list_of_dicts]

If you defined it in the * 20 method, the id is the same for each dict. In the list comprehension method, the id is unique.


Solution 2:

This it where the trouble starts: lod[j] = rrdict. lod itself is created properly with different dictionaries. Unfortunately, afterwards any references to the original dictionaries in the list get overwritten with a reference to rrdict. So in the end, the list contains only references to one single dictionary. Here is some more pythonic and readable way to solve your problem:

lod = [{} for _ in range(len(dataul))]
for rrdict in lod:
    for line in datakl:
        splt = line.split(',')
        rrdict[splt[0]] = splt[1:]

Solution 3:

You created the list of dictionaries correctly, as per other answer. However, when you are updating individual dictionaries, you completely overwrite the list. Removing noise from your code snippet:

lod = [{} for _ in range(whatever)]

for j in range(whatever):
    # rrdict = lod[j] # Uncomment this as a possible fix.
    for i in range(whatever):
        rrdict[somekey] = somevalue
    lod[j] = rrdict

Assignment on the last line throws away the empty dict that was in lod[j] and inserts a reference to the object represented by rrdict. Not sure what your code does, but see a commented-out line - it might be the fix you are looking for.


Post a Comment for "Python - Updating Value In One Dictionary Is Updating Value In All Dictionaries"