Drasive
Drasive

Reputation: 321

Serialize dictionary <int, custom_class> to XML [Python]

I am trying to cache the metadata of images that are downloaded from the internet using a dictionary (I'm not interested in the images themselves). The id (int) of the image is the key and a custom class representing the metadata is the value.
I want to write this dictionary to a file before program exit so I don't have to download the information again on the next startup, but I have some trouble serializing it.

So far I tried:

How can I serialize a dictionary (int, custom_class)? The serialized format should be human readable and must be deserializable.

I'm using Python 3.4 and external dependencies would be ok, as long as I can install them using pip.

Upvotes: 0

Views: 316

Answers (3)

Brendan Howell
Brendan Howell

Reputation: 329

You might try the built-in pickle module. If you use pickle.dumps(myobj, protocol=0) it returns a "human readable" serialized string. It is possible to read but most people will find it more difficult on your eyes than JSON or XML. The advantage is that pickle can deal with a lot of complex data structures that are problematic in JSON. It may also be attractive to avoid depending on another external library.

Upvotes: 1

Chris Arndt
Chris Arndt

Reputation: 2158

Use YAML via the PyYAML package. You can even create custom markup tags for your classes.

Upvotes: 0

mguijarr
mguijarr

Reputation: 7930

As you mentioned an external library is ok, use jsonpickle .

Upvotes: 2

Related Questions