1

I find that when I attempt to update values in a dictionary for items from another list, then only the last item in that last will be used to update the value. For example:

a=[{'a':1},{'a':2},{'a':3},{'a':4},{'a':5}]
b=[9, 8, 7, 6, 5]
changed = []
for items in a:
    for values in b:
        items.update({'a':values})
        changed.append(items)
print(changed)
[{'a': 5}, {'a': 5}, {'a': 5}, {'a': 5}, {'a': 5}, {'a': 5}, {'a': 5}, {'a': 5}, {'a': 5}, {'a': 5}, {'a': 5}, {'a': 5}, {'a': 5}, {'a': 5}, {'a': 5}, {'a': 5}, {'a': 5}, {'a': 5}, {'a': 5}, {'a': 5}, {'a': 5}, {'a': 5}, {'a': 5}, {'a': 5}, {'a': 5}]

I expected each value to replace each value in place of those in the dictionary.

tesla john
  • 310
  • 1
  • 2
  • 9
  • you are getting this error because of how list.append work, how it take reference object and add it to the list, since for internal iteration reference object is same, then for all object which are appending in changed list, having same reference has same value – sahasrara62 Dec 19 '22 at 10:19

0 Answers0