Any way to use a tuple as a key in a shelf? (Python)

I want to use a tuple (1,2,3) as a key using the shelf module in Python. I can do this with dictionaries:

d = {}
d[(1,2,3)] = 4

But if I try with a shelf:

s = shelve.open('myshelf')
s[(1,2,3)] = 4

I get: "TypeError: String or Integer object expected for the key, found tuple"

Any suggestions?

+5
source share
4 answers

According to the docs ,

values (not keys!) on a shelf can be essentially arbitrary Python Objects

: , . , str; , , repr, separator.join, , .. .

+7

repr() :

s[repr((1,2,3))] = 4
+6

, ? - repr str, . ( ) - Dewey decimal str .

+1

, .

I often use shelve and often want to use non-linear keys. I subclassed the shelve-modules class into a shelf that automatically converts non-string keys to string keys and returns them in their original form when prompted. It works well for standard immutable Python objects: int, float, string, tuple, boolean.

It can be found at: https://github.com/North-Guard/simple_shelve

0
source

All Articles