Not this one the other one, from a dictionary

Ross rossgk at gmail.com
Fri Sep 18 14:48:12 EDT 2009


Thanks Tim (and Ishwor) for the suggestions, those are structures  
that somewhat new to me - looks good!  I'll play with those.    At  
this rate I may soon almost know what I'm doing.

Rgds
Ross.


On 18-Sep-09, at 1:19 PM, Tim Chase wrote:

>> 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