简体   繁体   English

遍历字典值?

[英]Iterate through dictionary values?

Hey everyone I'm trying to write a program in Python that acts as a quiz game.大家好,我正在尝试用 Python 编写一个充当问答游戏的程序。 I made a dictionary at the beginning of the program that contains the values the user will be quizzed on.我在程序开始时制作了一个字典,其中包含用户将被测验的值。 Its set up like so:它的设置如下:

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

So I defined a function that uses a for loop to iterate through the dictionary keys and asks for input from the user, and compares the user input to the value matched with the key.所以我定义了一个函数,它使用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] )

This is working fine output looks like this:这是工作正常输出看起来像这样:

What is the Resolution of Full HD? 1920x1080
Nice Job!
What is the Resolution of VGA? 640x480
Nice Job!

So what I would like to be able to do is have a separate function that asks the question the other way, providing the user with the resolution numbers and having the user enter the name of the display standard.所以我希望能够做的是有一个单独的功能,以另一种方式提出问题,为用户提供分辨率编号并让用户输入显示标准的名称。 So I want to make a for loop but I don't really know how to (or if you even can) iterate over the values in the dictionary and ask the user to input the keys.所以我想做一个 for 循环,但我真的不知道如何(或者如果你甚至可以)迭代字典中的值并要求用户输入键。

I'd like to have output that looks something like this:我想要输出看起来像这样:

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

I've tried playing with for value in PIX0.values() and thats allowed me to iterate through the dictionary values, but I don't know how to use that to "check" the user answers against the dictionary keys.我试过for value in PIX0.values()使用for value in PIX0.values()这允许我遍历字典值,但我不知道如何使用它来“检查”用户对字典键的答案。 If anyone could help it would be appreciated.如果有人可以提供帮助,将不胜感激。

EDIT: Sorry I'm using Python3.编辑:对不起,我正在使用 Python3。

Depending on your version:根据您的版本:

Python 2.x: 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: 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))

You should also get in the habit of using the new string formatting syntax ( {} instead of % operator) from PEP 3101 :您还应该养成使用PEP 3101 中新的字符串格式语法( {}而不是%运算符)的习惯:

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

You could search for the corresponding key or you could "invert" the dictionary, but considering how you use it, it would be best if you just iterated over key/value pairs in the first place, which you can do with items() .您可以搜索相应的键,也可以“反转”字典,但考虑到您如何使用它,最好首先迭代键/值,您可以使用items() Then you have both directly in variables and don't need a lookup at all:然后你直接在变量中,根本不需要查找:

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

You can of course use that both ways then.你当然可以同时使用这两种方式。

Or if you don't actually need the dictionary for something else, you could ditch the dictionary and have an ordinary list of pairs.或者,如果您实际上不需要字典来做其他事情,您可以放弃字典并拥有一个普通的对列表。

You can just look for the value that corresponds with the key and then check if the input is equal to the key.您可以只查找与键对应的值,然后检查输入是否等于键。

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

Also, you will have to change the last line to fit in, so it will print the key instead of the value if you get the wrong answer.此外,您必须更改最后一行以适应,因此如果您得到错误的答案,它将打印键而不是值。

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

Also, I would recommend using str.format for string formatting instead of the % syntax.另外,我建议使用str.format进行字符串格式化而不是%语法。

Your full code should look like this (after adding in string formatting)您的完整代码应如下所示(添加字符串格式后)

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

If all your values are unique, you can make a reverse dictionary:如果您的所有值都是唯一的,您可以制作一个反向字典:

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

Result:结果:

>>> PIXO_reverse

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

Now you can use the same logic as before.现在您可以使用与以前相同的逻辑。

Create the opposite dictionary:创建相反的字典:

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

Then run the same code on this dictionary instead (using PIX1 instead of PIX0 ).然后代替(使用在此字典运行相同的代码PIX1代替PIX0 )。

BTW, I'm not sure about Python 3, but in Python 2 you need to use raw_input instead of input .顺便说一句,我不确定 Python 3,但在 Python 2 中你需要使用raw_input而不是input

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM