user14368706
user14368706

Reputation:

Saving python lists data as 1 pickle and then loading them back

in a part of a program i'm working on , I want to save 3 lists to 1 pickle and load them back at some later stage into those 3 lists , is it possible to save 3 lists to 1 pickle and read them back somehow ? would love to get an example of how to approach this !

Upvotes: 0

Views: 1519

Answers (1)

Zain Ul Abidin
Zain Ul Abidin

Reputation: 2710

To save your multiple lists e.g. 3 in your case in a single pickle file you must put all of your list in a dictionary and then save the single dictionary. After loading the dictionary back load your desired list back.

import pickle

def SaveLists(data):
    open_file = open('myPickleFile' "wb")
    pickle.dump(data, open_file)
    open_file.close()

def LoadLists(file):
    open_file = open(file, "rb")
    loaded_list = pickle.load(open_file)
    open_file.close()
    return loaded_list

#example to call the functions
cars = ['Toyota', 'Honda']
fruits = ['Apple', 'Cherry']

#create dictionary and add these lists
data = {}
data['cars'] = cars
data['fruits'] = fruits #add upto any number of lists

#save the data in pickle form
SaveLists(data)

#Load the data when desired
lists = LoadLists('myPickleFile')
print(lists['fruits']) #get your desired list

Upvotes: 1

Related Questions