我想以迭代方式存储数据。
如何在已包含字典的泡菜中添加一些新键?
例如
with open(filename_directory, 'wb') as f: pickle.dump({"a" : 1, "b":2 }, f) new_dict_ = {} for i in range(10): new_dict_ [i] = i with open(filename_directory, 'a') as f: pickle.dump( update_dict_with_my( new_dict_ ) , f)
答案 0 :(得分:0)
将其添加到泡菜文件中没有任何意义。
您可以:
像这样:
with open(filename_directory, 'wb') as f:
pickle.dump({"a" : 1, "b":2 }, f)
new_dict_ = {i:i for i in range(10)}
with open(filename_directory, 'rb') as f:
new_dict_.update(pickle.load(f))
with open(filename_directory, 'wb') as f:
pickle.dump( new_dict_ , f)
要以新密钥为最高优先级进行读取/更新/转储,请先阅读,更新和转储:
with open(filename_directory, 'rb') as f:
new_dict_ = update(pickle.load(f))
for i in range(10):
new_dict_ [i] = i
with open(filename_directory, 'wb') as f:
pickle.dump( new_dict_ , f)
请注意,如果您打算序列化字典中的基本类型,最好使用json
格式。至少转储的格式是可读的,甚至可以手工更新。