Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Load multiple Pickle objects into a single dictionary

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.

E.g.

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()

In essence, it works, but just overwrites the contents of my_dict rather than append each pickle object.

Thanks in advance for the help.

like image 846
Nunchux Avatar asked Jul 24 '26 23:07

Nunchux


1 Answers

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
like image 159
Vikas Ojha Avatar answered Jul 27 '26 14:07

Vikas Ojha