Python3字典迭代值?

Ben*_*ams 40 python dictionary loops key-value

嘿大家我正在尝试用Python编写一个程序来充当测验游戏.我在程序开头创建了一个字典,其中包含用户将被测验的值.它的设置如下:

PIX0 = {"QVGA":"320x240", "VGA":"640x480", "SVGA":"800x600"}
Run Code Online (Sandbox Code Playgroud)

所以我定义了一个函数,它使用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] )
Run Code Online (Sandbox Code Playgroud)

这是工作正常输出看起来像这样:

What is the Resolution of Full HD? 1920x1080
Nice Job!
What is the Resolution of VGA? 640x480
Nice Job!
Run Code Online (Sandbox Code Playgroud)

所以我希望能够做的是有一个单独的功能,以另一种方式询问问题,为用户提供分辨率编号并让用户输入显示标准的名称.所以我想创建一个for循环,但我真的不知道如何(或者你是否可以)迭代字典中的值并要求用户输入密钥.

我想要输出看起来像这样:

Which standard has a resolution of 1920x1080? Full HD
Nice Job!
What standard has a resolution of 640x480? VGA
Nice Job!
Run Code Online (Sandbox Code Playgroud)

我试过玩,for value in PIX0.values()这让我可以迭代字典值,但我不知道如何使用它来"检查"用户对字典键的答案.如果有人可以提供帮助,将不胜感激.

编辑:对不起,我正在使用Python3.

cho*_*own 74

取决于您的版本:

Python 2.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))
Run Code Online (Sandbox Code Playgroud)

Python 3.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))
Run Code Online (Sandbox Code Playgroud)

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

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

  • Python 3中不支持`iteritems()`,我相信OP正在使用它. (4认同)