1

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')
user3699853
  • 93
  • 1
  • 5
  • Why not use a dictionary instead of a list to store all of your sub-containers, and retrieve them with the appropriate keys? – MackM Oct 02 '14 at 18:08

2 Answers2

2

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

Leistungsabfall
  • 6,368
  • 7
  • 33
  • 41
pasichnyk.oleh
  • 222
  • 3
  • 8
  • The `*_` statement is explained further here: http://stackoverflow.com/questions/12555627/python-3-starred-expression-to-unpack-a-list – MackM Oct 02 '14 at 18:21
  • Thanks this is nice and easy to understand. Just what I was looking for. – user3699853 Oct 02 '14 at 18:36
1

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.

ASGM
  • 11,051
  • 1
  • 32
  • 53