Iterating Dictionaries in a Function

Delaney, Timothy C (Timothy) tdelaney at avaya.com
Sun May 9 19:36:54 EDT 2004


Michael Geary wrote:

> 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

What is that bare `except` doing in there?

A general tip - never use a bare except. There are exceptions to the
rule, but you need to really understand why not to use a bare except
before you do.

Also, since you're using a non-changing dictionary, it's best to only
create it once.

    OPTIONS = {'a': 1, 'rty': 4, 'er': 2}

    def findx (st):
        try:
            item = OPTIONS[st.lower()]
        except KeyError:
            print 'Item not found: %s' % (st,)
            return None
        else:
            print 'Item found: %s %s' % (st, item,)
            return item

or even better, don't bother catching the exception (I presume you're
only doing it for debugging, as with the printing):

    def findx (st):
        return OPTIONS[st.lower()]

which of course becomes

    OPTIONS[st.lower()]

As stated before, if there's a bug, it's almost certainly in your code
(most likely due to your misinderstanding of something). The Python
builtin types (e.g. dictionary) are *extensively* tested and used and
any such bug would have come to light a long time ago.

Tim Delaney




More information about the Python-list mailing list