Not this one the other one, from a dictionary

Ishwor ishwor.gurung at
Fri Sep 18 18:59:09 CEST 2009


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

Right. aDict[BigOne] will give you - 'bob' which may/maynot be what
you want by the looks of it, you want aDict[BigOne].

>>> aDict.keys()
['a', 'b']
>>> aDict.values()
['bob', 'stu']

keys() / values() return list so you do not have to worry about
explicitly getting list.

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

If you know the dictionary name in this case aDict (which you don't
mention you know or not), you can just traverse it using easily as
>>>for k in aDict:
     print k, aDict[k];

>>> [[i,a[i]] for i in aDict]
[['a', 'bob'], ['b', 'stu']]
>>> [[i,a[i]] for i in aDict][0]
['a', 'stu']
>>> [[i,a[i]] for i in aDict][0][0]
>>> [[i,a[i]] for i in aDict][0][1]

Ishwor Gurung

More information about the Python-list mailing list