Iterating Dictionaries in a Function

Michael Geary Mike at DeleteThis.Geary.com
Fri May 7 22:20:28 EDT 2004


> 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

p.s. In my other message I explained the bug in your code. Now let's talk
about the design a bit. Generally, you're *much* better off if you can let
the dict itself handle the lookup rather than iterating through it yourself.
In a large dict this will be much faster.

It looks like you want to do a case-insensitive lookup in the dict. The way
to handle this would be to convert keys to uppercase or lowercase when you
enter them into the dict, and do the same with values that you look up.

Here's your test case modified to work this way:

def findx(st):
    d = {'a': 1, 'rty': 4, 'er': 2}
    try:
        item = d[st.lower()]
    except:
        print 'Item not found:', st
    else:
        print 'Item found:', st, item
        return item

findx('a')
findx('ER')
findx('foo')

Which prints:

Item found: a 1
Item found: ER 2
Item not found: foo

-Mike





More information about the Python-list mailing list