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

Robert Sjoblom robert.sjoblom at gmail.com
Fri Mar 25 12:52:37 CET 2011


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

Which works fine, but the problem is that I need to ensure that every
key gets a value above 0; the try/except is clearly not doing that
(and it can't deal with b=int(input("Enter value:" )) because there's
no try for that, which I suppose there should be). How would I go
about making sure that each key gets a value above 0 in this case?
Also, is there a better way to do what I'm trying to do than what I've
come up with? I'm trying to translate a paper form into data arrays
for later use (and this particular part is simple in comparison to
some other parts where you get one name and multiple values to that
name, which I have no idea how to solve, but I figure one step at a
time, and the current step is this one), but I'm quite the newbie at
programming. Still.

best regards,
Robert S.


More information about the Tutor mailing list