0

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:

  • Serializing it to JSON using the builtin json module -> JSON doesn't support numbers as keys, serializing complex types seems quite complicated and unreliable
  • Serializing it to XML using various snippets that I found online -> complex type as the value generates a lot of trouble and most solutions seem to only work for specific use cases

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.

0

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.