keys problem

Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
Thread Solved

Join Date: May 2008
Posts: 16
Reputation: eibwen is an unknown quantity at this point 
Solved Threads: 3
eibwen eibwen is offline Offline
Newbie Poster

keys problem

 
0
  #1
Jun 6th, 2008
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
Reply With Quote Quick reply to this message  
Join Date: Jul 2006
Posts: 608
Reputation: jrcagle is on a distinguished road 
Solved Threads: 150
jrcagle jrcagle is offline Offline
Practically a Master Poster

Re: keys problem

 
1
  #2
Jun 6th, 2008
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:

  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
Reply With Quote Quick reply to this message  
Join Date: May 2008
Posts: 16
Reputation: eibwen is an unknown quantity at this point 
Solved Threads: 3
eibwen eibwen is offline Offline
Newbie Poster

Re: keys problem

 
0
  #3
Jun 6th, 2008
Thanks buddy!!!
That's exactly what I've been hunting for.
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:



Similar Threads
Other Threads in the Python Forum


Views: 487 | Replies: 2
Thread Tools Search this Thread



Tag cloud for Python
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC