Python3 Dictionary迭代值?

时间:2015-05-25 21:48:33

标签: python loops dictionary key-value

嘿大家我试图用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。

5 个答案:

答案 0 :(得分:67)

取决于您的版本:

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))

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))

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

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

答案 1 :(得分:3)

你可以搜索相应的键,或者你可以“反转”字典,但考虑到你如何使用它,最好是你首先迭代键/值 ,您可以使用items()。然后你直接在变量中,根本不需要查找:

for key, value in PIX0.items():
    NUM = input("What is the Resolution of %s?"  % key)
    if NUM == value:

你当然可以两种方式使用。

或者,如果你实际上并不需要其他的字典,你可以放弃字典,并有一个普通的对列表。

答案 2 :(得分:1)

您只需查找与该键对应的值,然后检查输入是否等于该键。

for key in PIX0:
    NUM = input("Which standard has a resolution of %s " % PIX0[key])
    if NUM == key:

此外,您必须更改最后一行以适应,因此如果您得到错误答案,它将打印键而不是值。

print("I'm sorry but thats wrong. The correct answer was: %s." % key )

另外,我建议使用str.format进行字符串格式化而不是%语法。

您的完整代码应如下所示(添加字符串格式后)

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

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

答案 3 :(得分:0)

如果您的所有值都是唯一的,则可以制作反向字典:

PIXO_reverse = {v: k for k, v in PIX0.items()}

结果:

>>> PIXO_reverse

{'320x240': 'QVGA', '640x480': 'VGA', '800x600': 'SVGA'}

现在你可以使用与以前相同的逻辑。

答案 4 :(得分:0)

创建相反的字典:

PIX1 = {}
for key in PIX0.keys():
    PIX1[PIX0.get(key)] = key

然后在此词典上运行相同的代码(使用PIX1代替PIX0)。

BTW,我不确定Python 3,但在Python 2中你需要使用raw_input而不是input