Not this one the other one, from a dictionary

Tim Chase python.list at tim.thechases.com
Fri Sep 18 19:19:08 CEST 2009


> Learning my way around list comprehension a bit.   I wonder if  
> someone has a better way to solve this issue.  I have a two element  
> dictionary, and I know one of the keys but not the other, and I want  
> to look up the other one.

Several ways occur to me.  Of the various solutions I played 
with, this was my favorite (requires Python2.4+ for generator 
expressions):

   d = {'a': 'alice', 'b':'bob'}
   known = 'a'
   other_key, other_value = (
     (k,v)
     for k,v
     in d.iteritems()
     if k != known
     ).next()

If you just want one or the other, you can simplify that a bit:

   other_key = (k for k in d.iterkeys() if k != known).next()
   other_key = (k for k in d if k != known).next()

or

   other_value = (v for k,v in d.iteritems() if k != known).next()

If you're using pre-2.4, you might tweak the above to something like

   other_key, other_value = [
     (k,v)
     for k,v
     in d.iteritems()
     if k != known
     ][0]
   other_key = [k for k in d if k != known)[0]
   other_value = [k for k in d.iteritems if k != known][0]

Hope this helps,

-tkc








More information about the Python-list mailing list