是否遍历字典值? [英] Iterate through dictionary values?

查看:64
本文介绍了是否遍历字典值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我正在尝试用Python语言编写一个程序,作为一个智力竞赛游戏。我在程序开始时制作了一本词典,其中包含用户将被测试的值。其设置如下:

PIX0 = {"QVGA":"320x240", "VGA":"640x480", "SVGA":"800x600"}

所以我定义了一个函数,该函数使用for循环迭代字典键并请求用户输入,并将用户输入与与键匹配的值进行比较。

for key in PIX0:
    NUM = input("What is the Resolution of %s?"  % key)
    if NUM == PIX0[key]:
        print ("Nice Job!")
        count = count + 1
    else:
        print("I'm sorry but thats wrong. The correct answer was: %s." % PIX0[key] )

正常工作,输出如下所示:

What is the Resolution of Full HD? 1920x1080
Nice Job!
What is the Resolution of VGA? 640x480
Nice Job!
因此,我希望能够做的是有一个单独的函数,以另一种方式询问问题,向用户提供分辨率编号,并让用户输入显示标准的名称。所以我想创建一个for循环,但我真的不知道如何(或者您是否可以)迭代字典中的值并要求用户输入键。

我希望输出如下所示:

Which standard has a resolution of 1920x1080? Full HD
Nice Job!
What standard has a resolution of 640x480? VGA
Nice Job!

我试过使用for value in PIX0.values(),这允许我迭代字典值,但我不知道如何使用它来根据字典键"检查"用户答案。如果有人能帮上忙,我将不胜感激。

编辑:很抱歉,我正在使用Python3。

推荐答案

取决于您的版本:

Python2.x:

for key, val in PIX0.iteritems():
    NUM = input("Which standard has a resolution of {!r}?".format(val))
    if NUM == key:
        print ("Nice Job!")
        count = count + 1
    else:
        print("I'm sorry but thats wrong. The correct answer was: {!r}.".format(key))

Python3.x:

for key, val in PIX0.items():
    NUM = input("Which standard has a resolution of {!r}?".format(val))
    if NUM == key:
        print ("Nice Job!")
        count = count + 1
    else:
        print("I'm sorry but thats wrong. The correct answer was: {!r}.".format(key))

您还应该养成使用PEP 3101中的新字符串格式语法({}而不是%运算符)的习惯:

https://www.python.org/dev/peps/pep-3101/

这篇关于是否遍历字典值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆