Python - 将多个 Pickle 对象加载到单个字典中 [英] Python - Load multiple Pickle objects into a single dictionary
问题描述
所以我的问题是...我有多个 Pickle 对象文件(它们是 Pickled Dictionaries),我想将它们全部加载,但基本上将每个字典合并到一个更大的字典中.
So my problem is this... I have multiple Pickle object files (which are Pickled Dictionaries) and I want to load them all, but essentially merge each dictionary into a single larger dictionary.
例如
我有 pickle_file1 和 pickle_file2 都包含字典.我想将 pickle_file1 和 pickle_file2 的内容加载到 my_dict_final 中.
I have pickle_file1 and pickle_file2 both contain dictionaries. I would like the contents of pickle_file1 and pickle_file2 loaded into my_dict_final.
编辑根据要求,这是我目前所拥有的:
EDIT As per request here is what i have so far:
for pkl_file in pkl_file_list:
pickle_in = open(pkl_file,'rb')
my_dict = pickle.load(pickle_in)
pickle_in.close()
本质上,它是有效的,但只是覆盖了 my_dict 的内容,而不是附加每个泡菜对象.
In essence, it works, but just overwrites the contents of my_dict rather than append each pickle object.
预先感谢您的帮助.
推荐答案
my_dict_final = {} # Create an empty dictionary
with open('pickle_file1', 'rb') as f:
my_dict_final.update(pickle.load(f)) # Update contents of file1 to the dictionary
with open('pickle_file2', 'rb') as f:
my_dict_final.update(pickle.load(f)) # Update contents of file2 to the dictionary
print my_dict_final
这篇关于Python - 将多个 Pickle 对象加载到单个字典中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!