[Tutor] using "in" with a dictionary

Steve Willoughby steve at alchemy.com
Wed Sep 29 00:12:50 CEST 2010


On 28-Sep-10 14:58, 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)]

Did you try this?  It looks fine to me as it is.
(1,2) is an immutable value (a tuple), so it is able to be used as a 
dictionary key.

if (1,2) in d

is perfectly valid, and would yield the True value as a result

if (1,2) in d: print d[(1,2)]

also is fine.  What specifically happens when you try this?


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

Sounds like there's more in your code than in your question.  If you 
give us a more complete picture of what you're doing, we can likely be 
more helpful to you.

if i=1 and j=2, then:

if (i,j) in d

would also be true.


More information about the Tutor mailing list