简体   繁体   English

如何在Python中的字典中为键添加值

[英]How to add a value to a key in dictionary in Python

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

There is no need to use key() . 不需要使用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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM