How to Use Pickle to Save a Dict (Or Any Other Python Object)

How can I use pickle to save a dict (or any other Python object)?

Try this:

import pickle

a = {'hello': 'world'}

with open('filename.pickle', 'wb') as handle:
pickle.dump(a, handle, protocol=pickle.HIGHEST_PROTOCOL)

with open('filename.pickle', 'rb') as handle:
b = pickle.load(handle)

print(a == b)

There's nothing about the above solution that is specific to a dict object. This same approach will will work for many Python objects, including instances of arbitrary classes and arbitrarily complex nestings of data structures. For example, replacing the second line with these lines:

import datetime
today = datetime.datetime.now()
a = [{'hello': 'world'}, 1, 2.3333, 4, True, "x",
("y", [[["z"], "y"], "x"]), {'today', today}]

will produce a result of True as well.

Some objects can't be pickled due to their very nature. For example, it doesn't make sense to pickle a structure containing a handle to an open file.

use pickle to save dictionary in python

You can use pickle.

import pickle
d = pickle.load(open('hash_db.pickle', 'rb'))
d['3gcdshj754']['last scanned time'] = '11:30 11/10/2015'
pickle.dump(d, open('hash_db.pickle', 'wb'))

But you might find the shelve module a little more convenient than direct use of pickle. It provides a persistent dictionary which seems to be exactly what you want. Sample usage:

import shelve
from datetime import datetime, timedelta

# create a "shelf"
shelf = shelve.open('hash_db.shelve')
shelf['123dfre345'] = {"file name": 'calc.pdf', "file size": 234, "last scanned time": datetime(2013, 12, 24, 12, 23)}
shelf['3gcdshj754'] = {"file name": 'star.pdf', "file size": 10, "last scanned time": datetime(2013, 10, 10, 10, 30)}
shelf.close()

# open, update and close
shelf = shelve.open('hash_db.shelve')
file_info = shelf['3gcdshj754']
file_info['last scanned time'] += timedelta(hours=+1, minutes=12)
shelf['3gcdshj754'] = file_info
shelf.close()

And that's it.

Save dict to pickle or write to file?

Python dict is implemented like json. You can use the json module to dump a dict into file, and load it back easily:

import json

d = {1: 'a', 2: 'b', 3: 'c'}

with open('C:\temp.txt', 'w') as file:
json.dump(d, file)

with open('C:\temp.txt', 'r') as file:
new_d = json.load(file)

>>> new_d
{u'1': u'a', u'3': u'c', u'2': u'b'}

How to put pickle dict value into an object

After the update, it looks like it is a list of dicts. Try:

strings = ["VALUE{}={}".format(i, d['value']) for i, d in enumerate(obj_dict)]

Pickle Dump to save an object within the class

You can pass self instead of obj. In other words:

def save(self, file_handler):
pickle.dump(self, file_handler)

The self points to the instance of that class. So what you basically do is calling pickle.dump and passing the instance to it together with the file_handler argument.



Related Topics



Leave a reply



Submit