[Tutor] using "in" with a dictionary

Sander Sweers sander.sweers at gmail.com
Wed Sep 29 00:22:02 CEST 2010


On 28 September 2010 23:58, Alex Hall <mehgcap at gmail.com> 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)]

This will work fine.

> This is false

Not it is not..
>>> d = {(1,2):"a",(3,4):"b"}
>>> (1,2) in d
True

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

>>> d = {1:"a",2:"b"}
>>> for x in range(1,4):
	if x in d:
		print "Found %s in dict d and has value %s" % (x, d[x])
	else:
		print "Value %s is not in dict d" % x

		
Found 1 in dict d and has value a
Found 2 in dict d and has value b
Value 3 is not in dict d

> When I tried "in" in the interpreter, I got something about builtin function
> not being iterable. TIA for any suggestions.

What was the code you tried out? Please do provide this as it helps
figure out what was going on.

Greets
Sander


More information about the Tutor mailing list