0

I have been given a file that contains two pickled objects- it was sent to me as a .pk file. I was told it had two objects, however, my attempt to unpikle these files is unsuccessful.

The first pickled object contains a dictionary of pairs of numbers with their roman numerals, and the second contains dictionary pairs of roman numerals with their numbers. How can I unpickle these two dictionaries separately?

This is what I have below, along with the error message I am receiving:

import pickle
x,y=pickle.load(open("C://Users//Documents//roman.pk", "rb"))
print(x,y)

Error Message:

ValueError: too many values to unpack (expected 2)
Megan
  • 231
  • 2
  • 5
  • 12
  • What happens if you just `pickle.load` to a single object, then look at what it contains? One of the dictionaries? Something else? You could also try calling `pickle.load` twice on the same file (i.e. `open` it once, then `load` from it twice). See http://stackoverflow.com/q/20716812/3001761 – jonrsharpe Apr 10 '15 at 10:47
  • If I run it with just one variable, then it gives me one of the dictionaries. If I try to load from it twice it just gives me the first dictionary twice. – Megan Apr 10 '15 at 10:59
  • Are you using `load(open(...))` both times? If so, that will reset the pointer to the start of the file. You need to **open it once** (using the `with` context manager, ideally - see http://stackoverflow.com/a/3287367/3001761). – jonrsharpe Apr 10 '15 at 11:02
  • Sorry, misunderstood your answer. Switched the format as you suggested and it is working! Thanks so much – Megan Apr 10 '15 at 11:02

2 Answers2

3

pickle.load will only load the first pickled object that it finds in the file. In your case, that's a dictionary with more than two keys, so x, y = pickle.load(...) fails because it's trying to unpack the dictionary's keys to the identifiers x and y.

Instead, you should open the file once, and load from it twice:

with open("...roman.pk") as file_:
    first_dict = pickle.load(file_)  # file pointer is now at end of first object
    second_dict = pickle.load(file_)  # read in second object

Alternatively, encourage whoever is supplying you with the file to put the two dictionaries into a single object, e.g. a tuple (first_dict, second_dict) and pickle that single object; this is much easier than relying on knowing exactly how many pickled objects are in the file.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
-1

pickle.load should load the data structure into one parameter. if you have 2 dictionary in roman.pk, it depends on how the 2 dictionary are grouped

e.g (dict1, dict2)

In this case: You probably want to try: (x,y)= pickle.load(open("C://Users//Documents//roman.pk", "rb")) print len(x) print len(y) To check if it loads correctly

user3483880
  • 119
  • 2