I meet a strange phenomenon while dealing with list of dictionary in python3
oldlist = [{'name':'cheng'}]
ages = '18,20'
newlist = []
for ele in oldlist:
for age in ages.split(','):
ele['age'] = age
newlist.append(ele)
print(newlist)
The result is :
[{'name': 'cheng', 'age': '20'}, {'name': 'cheng', 'age': '20'}]
What I am expected is
[{'name': 'cheng', 'age': '18'}, {'name': 'cheng', 'age': '20'}]
CodePudding user response:
That's because ele
is still referencing the same dictionary in the next iteration. You'll need to create a copy. One way is to cast it to a dict:
for ele in oldlist:
for age in ages.split(','):
ele['age'] = age
newlist.append(dict(ele))
or better yet, don't use oldlist
, simply use ele
itself for initialization:
ele = {'name':'cheng'}
for age in ages.split(','):
ele['age'] = age
newlist.append(ele)
Output:
[{'name': 'cheng', 'age': '18'}, {'name': 'cheng', 'age': '20'}]