[英]Pickle - Unable to correctly store appended dictionary to list
I am trying to save a list of multiple dictionaries in a pickle file and by able at any time to store a new appended dictionary in the list and save it in the pickle file and then load the pickle file as a list of dictionaries.我正在尝试将多个字典的列表保存在一个 pickle 文件中,并且能够随时在列表中存储一个新的附加字典并将其保存在 pickle 文件中,然后将 pickle 文件作为字典列表加载。 So far, the code behaves as follows:
到目前为止,代码的行为如下:
The first time I try to append a dictionary in the list, the pickle file looks like this (the data is saved succesfully):我第一次尝试在列表中附加字典时,pickle 文件如下所示(数据已成功保存):
Running info()......
===================================================
Existing data: []
===================================================
Running save_score()......
Inside try: {}
============================================
Existing data: [{}]
New data: {'ComputerName': 'computer name', 'PlayerName': 'user 1', 'ComputerScore': 3, 'PlayerScore': 1}
Saved Data: [{}, {'ComputerName': 'computer name', 'PlayerName': 'user 1', 'ComputerScore': 3, 'PlayerScore': 1}]
===================================================
The second time I try to append a dictionary in the list, the pickle file looks like this:我第二次尝试在列表中附加字典时,pickle 文件如下所示:
Running info()......
===================================================
Existing data: [[{}, {'ComputerName': 'computer name', 'PlayerName': 'user 1', 'ComputerScore': 3, 'PlayerScore': 1}]]
===================================================
Running save_score()......
Inside try: [{}, {'ComputerName': 'computer name', 'PlayerName': 'user 1', 'ComputerScore': 3, 'PlayerScore': 1}]
============================================
Existing data: [[{}, {'ComputerName': 'computer name', 'PlayerName': 'user 1', 'ComputerScore': 3, 'PlayerScore': 1}], [{}, {'ComputerName': 'computer name', 'PlayerName': 'user 1', 'ComputerScore': 3, 'PlayerScore': 1}]]
New data: {'ComputerName': 'computer name', 'PlayerName': 'user 1', 'ComputerScore': 3, 'PlayerScore': 1}
Saved Data: [[{}, {'ComputerName': 'computer name', 'PlayerName': 'user 1', 'ComputerScore': 3, 'PlayerScore': 1}], [{}, {'ComputerName': 'computer name', 'PlayerName': 'user 1', 'ComputerScore': 3, 'PlayerScore': 1}], {'ComputerName': 'computer name', 'PlayerName': 'user 1', 'ComputerScore': 3, 'PlayerScore': 1}]
===================================================
As you can see (the values in the dictionary are not a concern in the example above), instead of appending to the existing list, everytime, a new list inside the list is created.正如您所看到的(字典中的值在上面的示例中不是问题),而不是附加到现有列表,每次都会在列表中创建一个新列表。 So far, I have not managed to fix this and get the expected output.
到目前为止,我还没有设法解决这个问题并获得预期的输出。
The expected output should be:预期的输出应该是:
Saved Data: [{}, {'ComputerName': 'computer name', 'PlayerName': 'user 1', 'ComputerScore': 3, 'PlayerScore': 1}, {}, {'ComputerName': 'computer name', 'PlayerName': 'user 1', 'ComputerScore': 3, 'PlayerScore': 1}, {'ComputerName': 'computer name', 'PlayerName': 'user 1', 'ComputerScore': 3, 'PlayerScore': 1}]
Instead, the output is:相反,输出是:
Saved Data: [[{}, {'ComputerName': 'computer name', 'PlayerName': 'user 1', 'ComputerScore': 3, 'PlayerScore': 1}], [{}, {'ComputerName': 'computer name', 'PlayerName': 'user 1', 'ComputerScore': 3, 'PlayerScore': 1}], {'ComputerName': 'computer name', 'PlayerName': 'user 1', 'ComputerScore': 3, 'PlayerScore': 1}]
Code is as follows:代码如下:
import pickle
data = []
computer_name = "computer name"
username = "user 1"
computer_score = 3
human_score = 1
def save_score():
try:
existing_data = pickle.load(open("w6_project.p", "rb"))
print("Inside try: {}".format(existing_data))
data.append(existing_data)
except (OSError, IOError) as e:
pickle.dump({}, open("w6_project.p", "wb"))
new_data = {"ComputerName": computer_name, "PlayerName": username, "ComputerScore": computer_score, "PlayerScore": human_score}
print("============================================")
print("Existing data: {}".format(data))
data.append(new_data)
print("New data: {}".format(new_data))
pickle.dump(data, open("w6_project.p", "wb")) # Save the data into a pickle file
print("Saved Data: {}".format(data))
print("===================================================")
pass
def info():
try:
existing_data = pickle.load(open("w6_project.p", "rb"))
data.append(existing_data)
except (OSError, IOError) as e:
pickle.dump({}, open("w6_project.p", "wb"))
print("===================================================")
print("Existing data: {}".format(data))
print("===================================================")
pass
def main():
print("Running info()......\n")
info()
print("\nRunning save_score()......\n")
save_score()
if __name__ == "__main__":
main()
Problem is that you have two lists - data
and existing_data
- and you join them in wrong way.问题是您有两个列表 -
data
和existing_data
- 并且您以错误的方式加入它们。 Using append()
you put one list inside another list.使用
append()
将一个列表放入另一个列表中。 You should use extend()
to join them您应该使用
extend()
加入它们
data.extend(existing_data)
or shorter或更短
data += existing_data
But if you add new data after loading pickle then you should simply assing directly to variable但是如果你在加载 pickle 后添加新数据,那么你应该简单地直接赋值给变量
data = pickle.load(...)
EDIT: Minimal working example编辑:最小工作示例
import pickle
computer_name = "computer name"
username = "user 1"
computer_score = 3
human_score = 1
def save_score():
try:
data = pickle.load(open("w6_project.p", "rb"))
print("Inside try: {}".format(data))
except (OSError, IOError) as e:
data = []
new_data = {"ComputerName": computer_name, "PlayerName": username, "ComputerScore": computer_score, "PlayerScore": human_score}
data.append(new_data)
pickle.dump(data, open("w6_project.p", "wb")) # Save the data into a pickle file
print("============================================")
print("Existing Data: {}".format(data))
print("New Data: {}".format(new_data))
print("Saved Data: {}".format(data))
print("Length Data: {}".format( len(data) ))
print("===================================================")
def info():
try:
data = pickle.load(open("w6_project.p", "rb"))
except (OSError, IOError) as e:
data = []
print("===================================================")
print("Existing Data: {}".format(data))
print("Length Data: {}".format( len(data) ))
print("===================================================")
def main():
print("Running info()......\n")
info()
print("\nRunning save_score()......\n")
save_score()
if __name__ == "__main__":
main()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.