OK guys, I've hit a wall & can't find any info on what I'm wanting to do.
Maybe someone can help me out here or point me in the right direction please?

I have a shelve object- book.
If I do book.keys(), naturally I get a list of the keys-
When I do a book.keys(), I again get a list of those keys-
Is there a way to find out which key a key belongs to?

like - keyb belongs to what key? (keyb belongs to key1)


8 Years
Discussion Span
Last Post by eibwen

Well, that question may not have an answer if the values are not unique; for example, if

book = {'keya':valuea, 'keyb':valueb}


book = {'keya':valuec, 'keyd':valued}

then 'keya' cannot be mapped backwards.

But suppose that your values are unique. Then you could do this:

>>> import shelve  ## set up an example
>>> f= shelve.open("mydatabase")
>>> f['one'] = {1:2,3:4}
>>> f['two'] = {5:6,7:8}
>>> f.close()

>>> revdict = {}  ## Here's the reverse lookup code
>>> for key in f.keys():
	for subkey in f[key]:
		revdict[subkey] = key

>>> revdict
{1: 'one', 3: 'one', 5: 'two', 7: 'two'}

Basically, you're just reversing a dictionary. But again, you must be mathematically certain that your values are unique; else, you'll clobber things.


Votes + Comments
good reasoning and help

Thanks buddy!!!
That's exactly what I've been hunting for.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.