Reputation: 19
My question is that I want to make a program that displays names and scores. I want to get user input for a number and a name. If the name is in the dictionary, then it will append the value to the key but if it isn't, it will make a new key value pair. I have tried for hours but can't seem to do it.
class_1 = {'Farid':9, 'Manraj':5, 'Andy':7, 'Sajid':3}
score=int(input("Enter a number"))
name=input("What is your name?")
if name in class_1.key():
class_1[name]=score
else:
class_1[name]=score
Upvotes: 0
Views: 7662
Reputation: 6910
There is no need to use key()
. Just do:
if name in class_1:
And you are not really appending the new score to the existing one. You should do something like that:
class_1[name]+=score
So that you have
score=int(raw_input("Enter a number: "))
name=raw_input("What is your name?: ")
if name in class_1:
class_1[name]+=score
else:
class_1[name]=score
EDIT: If you want to append the new score to the old one and have both of the separately, you should define your dictionary values as list:
class_1 = {'Farid':[9], 'Manraj':[5], 'Andy':[7], 'Sajid':[3]}
And then, to append new score:
if name in class_1:
class_1[name].append(score)
Upvotes: 1