Why in Python, use of n * [dict()] to create nested dictionary causes same dictionary object?
>>> d = [(111, 2222), (3333, 4444), (555, 666)]
>>> d
[(111, 2222), (3333, 4444), (555, 666)]
>>> x = len(d) * [dict().copy()][:]
>>> x
[{}, {}, {}]
>>> x[0]['x'] = 'u'
>>> x # All entries of x gets modified
[{'x': 'u'}, {'x': 'u'}, {'x': 'u'}]
>>>
>>> x = [dict(), dict(), dict()]
>>> x
[{}, {}, {}]
>>> x[0]['x'] = 'u'
>>> x # only one entry of x gets modified
[{'x': 'u'}, {}, {}]
>>>
Copyright Notice:Content Author:「amulllb」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/22418390/same-dict-object-in-list-of-dict-python