colt.exe
colt.exe

Reputation: 728

Accessing dictionaries with field names

I have an unpickle function which returns a dict as:

def unpickle(file):
with open(file, 'rb') as fo:
    dict = pickle.load(fo, encoding='bytes')
return dict

and a function which reads pickled object with fieldnames (Don't know if this is the correct definiton):

def do_sth():
    all_data = unpickle('mypickle.pickle')
    image_filenames = all_data["Filenames"]
    conditions = all_data["Labels"] 

I have two lists as Filenames = ['001.png','002.png'] and Labels = ['0','1'] for brevity, that I need to pickle and save under mypickle.pickle so I can call them under the do_sth function. Till now what I did is:

data = [Filenames,Labels]
with open("mypickle.pickle", "wb") as f:
pickle.dump(data, f)

and

data = dict(zip(file_paths, labels))
with open("mypickle.pickle", "wb") as f:
pickle.dump(data, f)

But I'm getting KeyError :'Filenames'. Which structure shall I use to save these 2 lists so they may work properly. Thanks.

Upvotes: 0

Views: 415

Answers (1)

User15239563
User15239563

Reputation: 391

Change your function to this

def do_sth():
    all_data = unpickle('mypickle.pickle')     
    image_filenames = all_data[0]    
    conditions = all_data[1] 

Explanation

You saved pickle as list. When you load the pickle it is still a list.

or

Actually save it as a dict

data = {"Filenames": Filenames, "Labels": Labels}
with open("mypickle.pickle", "wb") as f:
    pickle.dump(data,  f)

Upvotes: 3

Related Questions