Iterating Dictionaries in a Function
Ryan Paul
segphault at sbcglobal.net
Fri May 7 22:15:25 EDT 2004
On Fri, 07 May 2004 18:23:10 -0700, Thinker wrote:
> 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?
its never going to make it past the first item, because you tell it to
return.
maybe you meant...?:
def findx(st):
d = {'a': 1, 'rty': 4, 'er': 2}
for item in d.keys():
print item
if item.upper() == st.upper():
print d[item]
return d[item]
return st
either way, looks like you should spend some time with the documentation.
More information about the Python-list
mailing list