我正在寻找一种用dict User更新列表listOfuser而不重写任何最后的索引的方法
[{'name': 'john', 'fimily': 'johny', 'studentId': '2120', 'age': 23},
{'name': 'mick', 'fimily': 'micky', 'studentId': '2121', 'age': 24}]
但结果是:
[{'name': 'mick', 'fimily': 'micky', 'studentId': '2121', 'age': 24},
{'name': 'mick', 'fimily': 'micky', 'studentId': '2121', 'age': 24}]
还有mycode:
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)
有什么办法吗?
您需要将字典的副本追加到列表中
listOfUser.append(UserInfo.copy())
输出
[{'name': 'john', 'fimily': 'johny', 'studentId': '2120', 'age': 23},
{'name': 'mick', 'fimily': 'micky', 'studentId': '2121', 'age': 24}]