-1

I am looking for a way to update list listOfuser with dict User without over writing any last index.

[{'name': 'john', 'fimily': 'johny', 'studentId': '2120', 'age': 23}, 
 {'name': 'mick', 'fimily': 'micky', 'studentId': '2121', 'age': 24}]

Result which I currently have:

[{'name': 'mick', 'fimily': 'micky', 'studentId': '2121', 'age': 24},
{'name': 'mick', 'fimily': 'micky', 'studentId': '2121', 'age': 24}]

Code snippet used to produce the said result:

 UserInfo = {}
 listOfUser = []
 UserInfo['name'] = "john"
 UserInfo['fimily'] = 'johny'
 UserInfo['studentId'] = '2120'
 UserInfo['age'] = 23
 listOfUser.append(UserInfo)
 print(listOfUser)
 UserInfo['name'] = "mick"
 UserInfo['fimily'] = 'micky'
 UserInfo['studentId'] = '2121'
 UserInfo['age'] = 24
 listOfUser.append(UserInfo)
 print(listOfUser)

is there any way ?

User9102d82
  • 1,172
  • 9
  • 19
  • 1
    dictionary are reference objects. if you add the reference to the list and change it afterwards your data is changed for whatever the reference points to. you can add a copy of the dictionary to your list or reset the dict to a new dictionary after adding it: `UserInfo = {}` after `listOfUser.append(UserInfo)`. See the dupes - lists are also reference objects - its the same principle – Patrick Artner Feb 04 '20 at 07:50

1 Answers1

2

You need to append a copy of the dictionary to the list

listOfUser.append(UserInfo.copy())

output

[{'name': 'john', 'fimily': 'johny', 'studentId': '2120', 'age': 23},
{'name': 'mick', 'fimily': 'micky', 'studentId': '2121', 'age': 24}]
Guy
  • 46,488
  • 10
  • 44
  • 88