![](/img/trans.png)
[英]How to print keys and values of a dictionary which is contained in a list in Python
[英]How to print dictionary keys and values in python
我必须制作一个程序,要求用户为每个学生输入学生姓名和成绩。 并将它们作为 [keys] 和 [values] 放入字典中。 当用户输入“q”时,程序退出,然后打印学生和他们的成绩,如下所示:
Student Grade
Student1 A
Student2 B
Student3 C
我的代码如下所示:
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
当我输入“q”时,程序应该打印学生姓名和成绩的键和值,但它什么也不打印
您可以像这样访问字典的键和值:
for k, v in mydict.iteritems():
print(k, v)
在 Python 3 中,这被更改/改进为:
for k, v in mydict.items():
print(k, v)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.