2009/9/18 Ross <ros...@gmail.com>:
>
> 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.
>
> So I have this dictionary:
>
> aDict = {'a': 'bob', 'b': 'stu'}
>
> I know that the dictionary contains two keys/value pairs,  but I don't know
> the values nor that the keys will be 'a' and 'b'.   I finally get one of the
> keys passed to me as variable BigOne. e.g.:
>
> BigOne = "a"
>
> The other key, call it  littleOne remains unknown.  It might be "b" but
> could be "c", "x", etc...   I later need to access both values...
>
> I have something that works, with list comprehension - but wonder if there's
> a more brief/elegant way to get there:
>
> BigValu = aDict[BigOne]
> temp =  [ thing for thing in aDict if thing != BigOne ]
> LittleValu = aDict[ temp[0] ]
>
> Any thoughts?
>
> - Ross.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Hi,
not a list comprehension, but another useful approach to get the
complement of (a) given item(s) might be the set operations.
(As you are working with dict keys, the requirements for set elements
are automatically fulfilled.

>>> data_dict = {'a': 'bob', 'b': 'stu'}
>>> not_wanted_key = "a"
>>> other_key = (set(data_dict.iterkeys()) - set([not_wanted_key,])).pop()
>>> other_key
'b'
>>> data_dict[other_key]
'stu'
>>>

vbr
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to