Python3 字典遍历值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30446449/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python3 Dictionary iterate through values?
提问by Ben Williams
Hey everyone I'm trying to write a program in Python that acts as a quiz game. 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:
大家好,我正在尝试用 Python 编写一个充当问答游戏的程序。我在程序开始时制作了一个字典,其中包含用户将被测验的值。它的设置如下:
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. If anyone could help it would be appreciated.
我试过玩,for value in PIX0.values()
这允许我遍历字典值,但我不知道如何使用它来“检查”用户对字典键的答案。如果有人可以提供帮助,将不胜感激。
EDIT:Sorry I'm using Python3.
编辑:对不起,我正在使用 Python3。
采纳答案by chown
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 中新的字符串格式化语法({}
而不是%
运算符)的习惯:
回答by Stefan Pochmann
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 pairsin the first place, which you can do with items()
. Then you have both directly in variables and don't need a lookup at all:
您可以搜索相应的键,也可以“反转”字典,但考虑到您如何使用它,最好首先迭代键/值对,您可以使用items()
. 然后你直接在变量中,根本不需要查找:
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.
或者,如果您实际上不需要字典来做其他事情,您可以放弃字典并拥有一个普通的对列表。
回答by michaelpri
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))
回答by Mike Müller
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.
现在您可以使用与以前相同的逻辑。
回答by barak manos
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
。