Home > front end >  How to save ChainMap objects?
How to save ChainMap objects?

Time:02-13

I have a list of ChainMap objects in python that I'm using for analysis. I need to save them to disk somehow for later use. Is there any possibility to do this?

CodePudding user response:

You can use the pickle lib. Here is a toy example that saves cm.pickle as a binary file and reads it again as the unpickled variable.

from collections import ChainMap
import pickle

nums = {"one": 1, "two": 2}
lets = {"a": "A", "b": "B"}

cm = ChainMap(nums, lets)

with open('cm.pickle', 'wb') as f:
    pickle.dump(cm, f)

with open('cm.pickle', 'rb') as f:
    unpickled = pickle.load(f)

print(unpickled)
ChainMap({'one': 1, 'two': 2}, {'a': 'A', 'b': 'B'})
  • Related