unicode and shelve

vincent wehren vincent at visualtrans.de
Tue Jun 29 10:32:56 EDT 2004


Guy Robinson wrote:
> Hello,
> 
> When I try and create a unicode key with a shelve I get the following 
> error:
> 
> "TypeError: String or Integer object expected for key, unicode found"
> 
> Is there anyway I can use unicode keys with shelve's?

Well, not "Python unicode objects". You can however encode the python
unicode strings to utf-8 or utf-16 if retaining your unicode characters 
is what you are looking for. Ofcourse, for lookups, you need to do the 
same thing.

If you choose to use UTF-16, you might want to consider indicating 
endianess when encoding (e.g. key = key.encode("utf-16le")) to avoid the 
byte-order mark being written at the start of each key. Something like 
the following should work:

# -*- coding: cp1252 -*-
import shelve
d = shelve.open("test.dat")
key = u"Übersetzung".encode("utf-16le")
d[key] = "Translator"


HTH,

--
Vincent Wehren


















> 
> TIA,
> 
> Guy



More information about the Python-list mailing list