[英]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.