[Tutor] if value not in dictionary, do a?

Hugo Arts hugo.yoshi at gmail.com
Fri Mar 25 13:13:44 CET 2011

On Fri, Mar 25, 2011 at 12:52 PM, Robert Sjoblom
<robert.sjoblom at gmail.com> wrote:
> Hi again, list! A quick question about dictionary behaviour. I have a
> dictionary of keys, and the user should be able to enter values into
> said dictionary. My idea was this:
> def addData(key, value):
>    dictionary[key] += int(value)
>    return None
> dictionary = {"a":0, "b":0, "c":0, "d":0}
> for key in dictionary:
>    a = input("Enter key: ")
>    b = int(input("Enter value: "))
>    try:
>        addData(a, b)
>    except:
>        continue

Why are you asking for the user to enter a key? you're iterating over
all keys in the dictionary, so there's no need to ask the user for
keys, you already know them. Why not do this:

b = int(input("Enter value for key %s: " % key))
dictionary[key] = b

This way you can be sure a value is entered for every key, and no key
is entered twice. You'll still need to check the user doesn't just
enter 0 though.

Another few points:
* you don't ave to add return None in that function. If you get to the
end of a function and there's no return statement, None is
automatically returned.
* don't use a blank except. *ever*. If you really want to catch
everything, do "except Exception:" otherwise, catch what you expect to
be thrown in this case, "except KeyError"


More information about the Tutor mailing list