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

col speed ajarncolin at gmail.com
Fri Mar 25 13:07:49 CET 2011

I am a newbie too, but....
from collections import defaultdict

Then you can do:
data = defaultdict(int)
Everything (all keys) start at 0, so you can do "+=" with no problem.

I'm sure somebody else has a better solution though!


On 25 March 2011 18:52, 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
> 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.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110325/4b668dab/attachment.html>

More information about the Tutor mailing list