943,603 Members | Top Members by Rank

Ad:
  • Python Discussion Thread
  • Marked Solved
  • Views: 597
  • Python RSS
Jun 6th, 2008
0

keys problem

Expand Post »
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- ['key1', 'key2', etc...]
When I do a book['key1'].keys(), I again get a list of those keys- ['keya', 'keyb', etc...]
Is there a way to find out which key a key belongs to?

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

Thanks
Similar Threads
Reputation Points: 10
Solved Threads: 3
Newbie Poster
eibwen is offline Offline
16 posts
since May 2008
Jun 6th, 2008
1

Re: keys problem

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

book['key1'] = {'keya':valuea, 'keyb':valueb}

and

book['key2'] = {'keya':valuec, 'keyd':valued}

then 'keya' cannot be mapped backwards.

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

Python Syntax (Toggle Plain Text)
  1. >>> import shelve ## set up an example
  2. >>> f= shelve.open("mydatabase")
  3. >>> f['one'] = {1:2,3:4}
  4. >>> f['two'] = {5:6,7:8}
  5. >>> f.close()
  6.  
  7. >>> revdict = {} ## Here's the reverse lookup code
  8. >>> for key in f.keys():
  9. for subkey in f[key]:
  10. revdict[subkey] = key
  11.  
  12.  
  13. >>> revdict
  14. {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.

Jeff
Reputation Points: 92
Solved Threads: 156
Practically a Master Poster
jrcagle is offline Offline
608 posts
since Jul 2006
Jun 6th, 2008
0

Re: keys problem

Thanks buddy!!!
That's exactly what I've been hunting for.
Reputation Points: 10
Solved Threads: 3
Newbie Poster
eibwen is offline Offline
16 posts
since May 2008

This thread is solved

Either the thread starter or a moderator has marked this thread as solved. You can most likely trust the responses and answers given. There is most likely no reason for any further responses to be posted here. If you have a related question, please start a new thread in this forum instead.

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in Python Forum Timeline: Running Python Code in a Webpage
Next Thread in Python Forum Timeline: Eratosthenes sieve





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC