[Tutor] pickle in unicode format

Kent Johnson kent37 at tds.net
Tue Apr 5 17:50:04 CEST 2005


BRINER Cedric wrote:
> hi,
> 
> I have this dictionnary :
> 
> a={'partition': u'/export/diskH1/home_evol/ricquebo',
>  'rsmFirstname': u'Fran\xe7ois',
>  'rsmLastname': u'Ricquebourg',
>  'size': u'8161222.0',
>  'size_max': '1'}
> 
> and I'd like to *serialize* it with pickle and that the output format
> will be of type unicode.

I'm not sure what you mean by this. Do you mean that you want the actual pickled data to be a 
unicode string? Or that you want to be able to pickle something that contains unicode strings?
> 
> unicode(pickle.dumps(a)) doesn't work !

pickle.dumps() doesn't return a value, it puts the data into 'a' which must be a file-like object.

> or
> pickle.dumps(a,protocol=2,bin='V')
> 
> doesn't seem to work :(

The bin parameter is replaced by the protocol parameter, you don't need to use both. Also the bin 
parameter takes a True or False value so passing it a string is kind of strange.

Can you say some more about the problem you are trying to solve? If you are just trying to pickle 
and unpickle the dictionary above then pickle.dumps() and pickle.loads() should work:

  >>> a={'partition': u'/export/diskH1/home_evol/ricquebo',
  ...  'rsmFirstname': u'Fran\xe7ois',
  ...  'rsmLastname': u'Ricquebourg',
  ...  'size': u'8161222.0',
  ...  'size_max': '1'}
  >>> a
{'rsmLastname': u'Ricquebourg', 'rsmFirstname': u'Fran\xe7ois', 'partition': 
u'/export/diskH1/home_evol/ricquebo', 'size_max': '1', 'size': u'8161222.
0'}

  >>> import pickle
  >>> s = pickle.dumps(a)
  >>> s
"(dp0\nS'rsmLastname'\np1\nVRicquebourg\np2\nsS'rsmFirstname'\np3\nVFran\xe7ois\np4\nsS'partition'\np5\nV/export/diskH1/home_evol/ricquebo\np6\nsS'siz
e_max'\np7\nS'1'\np8\nsS'size'\np9\nV8161222.0\np10\ns."

  >>> b = pickle.loads(s)
  >>> b
{'rsmLastname': u'Ricquebourg', 'rsmFirstname': u'Fran\xe7ois', 'partition': 
u'/export/diskH1/home_evol/ricquebo', 'size_max': '1', 'size': u'8161222.
0'}
  >>> b == a
True
  >>>

Kent



More information about the Tutor mailing list