Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Solution to a list dict base problem, https://stackoverflow.com/questions/56814001/updating-json-fields-with-values-from-list (Unfortunately, the guy deleted the post)

Problem

In Python, list, dictionary are reference types. So if you will append the same dictionary to a list and if you will make any change to any of the dictionary, it will reflect in all other as well because all are pointing to the same memory location.

>>> l = [{"name": "Raghavendra Thakur", "age": 27}] * 4
>>> 
>>> l
[{'name': 'Raghavendra Thakur', 'age': 27}, {'name': 'Raghavendra Thakur', 'age': 27}, {'name': 'Raghavendra Thakur', 'age': 27}, {'name': 'Raghavendra Thakur', 'age': 27}]
>>> 
>>> l[0]
{'name': 'Raghavendra Thakur', 'age': 27}
>>> 
>>> l[0]["name"] = "Malinikesh Agrawani"
>>> 
>>> l
[{'name': 'Malinikesh Agrawani', 'age': 27}, {'name': 'Malinikesh Agrawani', 'age': 27}, {'name': 'Malinikesh Agrawani', 'age': 27}, {'name': 'Malinikesh Agrawani', 'age': 27}]
>>> 
>>> 

Simple solution

Please take care while forming the list

>>> # Let's stop above problem
... 
>>> l2 = []
>>> for i in range(4):
...     l2.append({"name": "Raghavendra Thakur", "age": 27})
... 
>>> l2
[{'name': 'Raghavendra Thakur', 'age': 27}, {'name': 'Raghavendra Thakur', 'age': 27}, {'name': 'Raghavendra Thakur', 'age': 27}, {'name': 'Raghavendra Thakur', 'age': 27}]
>>> 
>>> l2[0]
{'name': 'Raghavendra Thakur', 'age': 27}
>>> 
>>> l2[0]['name'] = "Malinikesh Agrawani"
>>> 
>>> l2
[{'name': 'Malinikesh Agrawani', 'age': 27}, {'name': 'Raghavendra Thakur', 'age': 27}, {'name': 'Raghavendra Thakur', 'age': 27}, {'name': 'Raghavendra Thakur', 'age': 27}]
>>> 
>>> 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.