user3699853
user3699853

Reputation: 93

unpickle list of dictionaries

I have a file that has some dicts and list that I pickle (roughly 900 lines) that I don't want in my main script. I then do the following.

myDicts = [DictOne, DictTwo, ListOne, ListTwo]
pickle.dump(myDicts, open("all.p", "wb"))

this creates the all.p file which I load in my script.

myDicts = pickle.load( open ("all.p", "rb") )

What I don't know is how to access these Dictionaries now. How do I use the imported dictionaries? I can print the length or the entire list so I know the data is there, but I have no clue on how to access it, checked out some of the post here but I can't figure it out.

I tried

I would normally do something like this:

if blah == "blah" and sum([x in "text" for x in DictOne]):

so I tried doing this:

if blah == "blah" and sum([x in "text" for x in myDicts(DictOne)]):

Is there a easy way to just save the dictionary/list back to a dictionary/list?

DictOne = myDicts('DictOne')
ListOne = myDicts('ListOne')

or if I have

if flaga:
   list=mydicts('ListOne')
elif flagb:
   list=mydicts('ListTwo')

Upvotes: 1

Views: 833

Answers (2)

pasichnyk.oleh
pasichnyk.oleh

Reputation: 242

You can easily unpack values like this:

DictOne, DictTwo, *_ = pickle.load( open ("all.p", "rb") )

Instead of *_ you can add the next ListOne, ListTwo if you need.

Note: For using *_ you will need Python 3.x.x

Upvotes: 2

ASGM
ASGM

Reputation: 11381

If you pickled your original list, you can access the objects stored in that list by referencing their index in the list. So if you want to get DictTwo, you can call myDicts[1] (because you count starting at 0).

If you want to be able to call it using a string-based name, you can make the original container a dictionary instead of a list (as @MackM suggests in a comment):

myDicts = {"DictOne": DictOne, "DictTwo": DictTwo, "ListOne": ListOne, "ListTwo": ListTwo}

You might want to read up on calling basic python data structures.

Upvotes: 1

Related Questions