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

Rafael Durán Castañeda rafadurancastaneda at gmail.com
Fri Mar 25 13:26:33 CET 2011

```In addition I think defaultdict doesn't avoid neither entering negatives nor
something that isn't an integer, you could try something like this:

>>> dictionary = {}
>>> for _ in range(4):
key = input("Enter key: ")
value = 0
while value <= 0:
try:
value = int(input("Enter a value: "))
except ValueError:
print("Value must be an integer!")
else:
if(value <= 0):
print("Value must be greater than 0")
dictionary[key] = value

Enter key: a
Enter a value: 1
Enter key: b
Enter a value: 0
Value must be greater than 0
Enter a value: -1
Value must be greater than 0
Enter a value: sdf
Value must be an integer!
Enter a value: 2
Enter key: c
Enter a value: 3
Enter key: d
Enter a value: 4
>>> dictionary
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
>>>

2011/3/25 Hugo Arts <hugo.yoshi at gmail.com>

> 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
> >
> >    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:
> >    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"
>
> Hugo
> _______________________________________________
> 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/46234beb/attachment-0001.html>
```