如何在python中打印字典键和值

塔雷克·莫斯塔法(Tarek Mostafa)

我必须编写一个程序,要求用户为每个学生输入学生姓名及其等级。并将它们作为[键]和[值]放入字典中。当用户输入“ 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”时,程序应打印键和值(即学生姓名及其等级),但不打印任何内容

尤金·K

您可以像这样访问字典的键和值:

for k,v in mydict.iteritems():
    print(k, v)

在Python 3中,将其更改/改进为:

for k,v in mydict.items():
    print(k,v)

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

如何在Python中打印字典的键?

来自分类Dev

如何在Python中打印字典

来自分类Dev

通过值python打印字典键和值

来自分类Dev

如何打印字典的键,在值列表中搜索值

来自分类Dev

Python:无法打印字典键和值

来自分类Dev

如何在字典列表中打印字典值?

来自分类Dev

按降序打印字典中的键和值,无需导入运算符(Python)

来自分类Dev

如何打印Python列表中包含的字典的键和值

来自分类Dev

Python:如何打印字典值

来自分类Dev

Python:如何打印字典值

来自分类Dev

Python:在函数中打印字典值

来自分类Dev

如何在Python中迭代字典以获取键和值?

来自分类Dev

如何使用字典值打印与 Python 列表中的键关联的键和多个值?

来自分类Dev

如何在python中没有方括号和撇号的新行中打印字典列表

来自分类Dev

如何在jinja2的列表中打印字典?

来自分类Dev

如何使用python搜索和打印字典?

来自分类Dev

Python:如何根据特定键值仅打印字典中的实际值?

来自分类Dev

从字典中打印键和值

来自分类Dev

打印字典值的集合-python

来自分类Dev

在Jinja中打印字典值

来自分类Dev

在Swift中打印字典值

来自分类Dev

在列表中打印字典项的值

来自分类Dev

在Swift中打印字典值

来自分类Dev

如何在python中以唯一键和多个值将输出作为字典返回?

来自分类Dev

从没有Unicode的键中打印字典值[u'STRING]

来自分类Dev

如何在Meteor模板中打印键和值?

来自分类Dev

在 Python 3 中打印字典

来自分类Dev

如何从字典中打印键,其中字典的值在python中列出

来自分类Dev

如何在Python中使用键扩展字典中的值