Professional Documents
Culture Documents
Just like with JSON files, you pickle with pickle.dump(obj, file), and unpickle with pickle.load(file). That’s it, really! Just
remember that file needs to be a binary file .
import pickle
courses = {
70053: {"lecturer": "Josiah Wang", "title": "Python Programming"},
70051: {"lecturer": "Robert Craven", "title": "Symbolic AI"}
}
Exercise
Here is a quick exercise. Your task:
pickle vector in the code below and save it as vectors.pkl.
then load the vector back from the file you just saved, and examine that the results are the same as
expected.
Note that this time you are pickling something more complex: a list of Vectors (your custom class).
import pickle
1 class Vector:
2 def __init__(self, x, y):
3 self.x = x
4 self.y = y
5
6 def __str__(self):
7 return f"Vector ({self.x}, {self.y})"
8
9 def __repr__(self):
10 """ This makes the unique string representation
11 of the object instance look more readable
12 """
13 return str(self)
14
15
16 vector1 = Vector(2, 3)
17 vector2 = Vector(4, 3)
18 vector = [vector1, vector2]
19
20 # TODO: Save vector to disk.
21 ????
22
23 # TODO: Load pickled file that you saved earlier from disk
24 pickled_vectors = ????
25
26 print(pickled_vectors) ## [Vector (2, 3), Vector (4, 3)]
27
28 print(type(pickled_vectors)) ## <class 'list'>
29
30
Peek at solution
Previous Next