unicode and shelve

G

Guy Robinson

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?

TIA,

Guy
 
V

vincent wehren

Guy said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,202
Messages
2,571,057
Members
47,661
Latest member
FloridaHan

Latest Threads

Top