Python pickling returning a string when I've pickled a dict?
I'm currently learning about pickling in Python and I'm confused with an error I'm getting complaing that the unpickled variable I'm initalizing does not have a particular attribute I'm wanting to use.
I'm pickling a dictionary of the script's data and then trying to unpickle.load it back using the following code:
def loadData():
global script_data_filepath
with open(script_data_filepath) as script_data_file:
data_to_load = pickle.load(script_data_file)
for data_item in data_to_load.items():
print(data_item[0])
print(data_item[1])
The problem i开发者_开发问答s that Python is saying that items() is not an attribute of data_to_load because data_to_load is of type 'str'. In the code I've given this is the first time that data_to_load is declared, I pressumed that it would dynamically take whatever type is assigned to it (which should be a dictionary as that's what I know will be loaded from this file).
That should work. The code you posted is fine. How are you dumping it? You're using pickle.dump
, not pickle.dumps
for a string? Your problem is almost certainly in the dumping code.
>>> import cPickle
>>> foo = {4:2}
>>> cPickle.dump(foo, open('foo.pickle', 'wb'))
>>> data_to_load = cPickle.load(open('foo.pickle'))
>>> data_to_load.items()
[(4, 2)]
精彩评论