[英]How to print dictionary keys and values in python
I have to make a program which asks the user to enter a student name, and their grade, for every student.我必须制作一个程序,要求用户为每个学生输入学生姓名和成绩。 And put them as [keys] and [values] in a dictionary.并将它们作为 [keys] 和 [values] 放入字典中。 And when the user enters 'q' the program quits and then prints the students and their grades such as this:当用户输入“q”时,程序退出,然后打印学生和他们的成绩,如下所示:
Student Grade
Student1 A
Student2 B
Student3 C
My code looks like this:我的代码如下所示:
student_grades = {}
while True:
## Get the Name [key in dictionary] of the student
name = raw_input("Please give me the name of the student (press q to quit): \n")
if name == 'q':
print "Okay, printing grades! \n"
for x in student_grades:
print student_grades.keys() + student_grades.values()
break
# Chcek if name isn't valid
elif name.isdigit():
print "Sorry, {} isn't valid".format(name)
name = raw_input("Please give me the name of the student (press q to quit): \n")
## Get the grade [value in dictionary] of the student
grade = raw_input("Please give me their grade: (e.g 'A', 'B', 'C', 'D', 'F') \n")
# Check if grade isn't valid
if not grade in ['A', 'B', 'C', 'D', 'F']:
print "Sorry, {} isn't valid".format(grade)
grade = raw_input("Please give me their grade: (e.g 'A', 'B', 'C', 'D', 'F') \n")
# Assign Name to Grade
student_grades[name] = grade
When I enter 'q' the program should print the keys and values which are the student name and their grade, but it prints nothing当我输入“q”时,程序应该打印学生姓名和成绩的键和值,但它什么也不打印
You can access the keys and values of a dictionary like this:您可以像这样访问字典的键和值:
for k, v in mydict.iteritems():
print(k, v)
In Python 3 this is changed/bettered to:在 Python 3 中,这被更改/改进为:
for k, v in mydict.items():
print(k, v)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.