'Python3 List of Dictionary
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'}]
Solution 1:[1]
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'}]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
