Iterating Dictionaries in a Function
David M. Cooke
cookedm+news at physics.mcmaster.ca
Mon May 10 15:15:55 EDT 2004
At some point, "Delaney, Timothy C (Timothy)" <tdelaney at avaya.com> wrote:
> 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()]
Or, without exceptions, and returning None like before,
def findx(st):
return OPTIONS.get(st.lower(), None)
--
|>|\/|<
/--------------------------------------------------------------------------\
|David M. Cooke
|cookedm(at)physics(dot)mcmaster(dot)ca
More information about the Python-list
mailing list