Iterating Dictionaries in a Function

Michael Geary Mike at DeleteThis.Geary.com
Fri May 7 21:55:49 EDT 2004


> I could not get this simple code work. I am guessing that
> there is a bug in the Python dictionary iterator.
>
> def findx(st):
>         d = {'a': 1, 'rty': 4, 'er': 2}
>         for item in d.keys():
>                 print item
>                 if cmp(item.upper(),st.upper()) == 0:
>                         print d[item]
>                         return d[item]
>                 else:
>                         return st
>
>
> When I call:
> findx('a')
> it finds the key. But when I call:
> findx('er')
> it does not find anything since it does not iterate; it just checks
> the first item in the dictionary.
>
> Does anyone see where the bug is?

Here's a tip: When I think there is a bug in Python (or C++, or whatever
language I'm using), sometimes there is. But usually the bug is in *my*
code. :-)

In this code, your for loop always returns during the first iteration. This
is because you have return statements in both the if and else clauses, so
whether the if test succeeds or fails, the function returns immediately. The
loop never even looks at entries in the dict after the first one.

-Mike





More information about the Python-list mailing list