Iterate through dictionary values?

Ben Williams picture Ben Williams · May 25, 2015 · Viewed 98.5k times · Source

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:

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

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.

EDIT: Sorry I'm using Python3.

Answer

chown picture chown · May 25, 2015

Depending on your version:

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

You should also get in the habit of using the new string formatting syntax ({} instead of % operator) from PEP 3101:

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