遍历字典值? - python

大家好,我想用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。

参考方案

根据您的版本:

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/

Python uuid4,如何限制唯一字符的长度 - python

在Python中,我正在使用uuid4()方法创建唯一的字符集。但是我找不到将其限制为10或8个字符的方法。有什么办法吗?uuid4()ffc69c1b-9d87-4c19-8dac-c09ca857e3fc谢谢。 参考方案 尝试:x = uuid4() str(x)[:8] 输出:"ffc69c1b" Is there a way to…

Python-如何检查Redis服务器是否可用 - python

我正在开发用于访问Redis Server的Python服务(类)。我想知道如何检查Redis Server是否正在运行。而且如果某种原因我无法连接到它。这是我的代码的一部分import redis rs = redis.Redis("localhost") print rs 它打印以下内容<redis.client.Redis o…

Python-crontab模块 - python

我正在尝试在Linux OS(CentOS 7)上使用Python-crontab模块我的配置文件如下:{ "ossConfigurationData": { "work1": [ { "cronInterval": "0 0 0 1 1 ?", "attribute&…

Python:检查是否存在维基百科文章 - python

我试图弄清楚如何检查Wikipedia文章是否存在。例如,https://en.wikipedia.org/wiki/Food 存在,但是https://en.wikipedia.org/wiki/Fod 不会,页面只是说:“维基百科没有此名称的文章。”谢谢! 参考方案 >>> import urllib >>> prin…

Python GPU资源利用 - python

我有一个Python脚本在某些深度学习模型上运行推理。有什么办法可以找出GPU资源的利用率水平?例如,使用着色器,float16乘法器等。我似乎在网上找不到太多有关这些GPU资源的文档。谢谢! 参考方案 您可以尝试在像Renderdoc这样的GPU分析器中运行pyxthon应用程序。它将分析您的跑步情况。您将能够获得有关已使用资源,已用缓冲区,不同渲染状态上…