[Tutor] using "in" with a dictionary

Steven D'Aprano steve at pearwood.info
Wed Sep 29 00:15:26 CEST 2010


On Wed, 29 Sep 2010 07:58:28 am Alex Hall wrote:
> Hi all, yet again:
> I have a dictionary that will look something like:
> d={
>  (1,2):"a",
>  (3,4):"b"
> }
>
> How can I say:
> if (1,2) in d: print d[(1,2)]

Exactly like that:


>>> d = {(1,2): 'a', (3,4): 'b'}
>>> if (1,2) in d: print d[(1,2)]
...
a


> This is false, so I expect to have to use d.keys, but I am not quite
> sure how. I will be using this in a loop, and I have to know if there
> is a key in the dictionary called (i,j) and, if there is, I have to
> grab the value at that slot. If not I have to print something else.
> When I tried "in" in the interpreter, I got something about builtin
> function not being iterable. TIA for any suggestions.

Without knowing exactly what you wrote, and what error you got, I have 
no clue why you got that.



-- 
Steven D'Aprano


More information about the Tutor mailing list