[python] Iterate through dictionary values?

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.

This question is related to python python-3.x loops dictionary key-value

The answer is


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.


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

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

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

BTW, I'm not sure about Python 3, but in Python 2 you need to use raw_input instead of input.


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to python-3.x

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation Replace specific text with a redacted version using Python Upgrade to python 3.8 using conda "Permission Denied" trying to run Python on Windows 10 Python: 'ModuleNotFoundError' when trying to import module from imported package What is the meaning of "Failed building wheel for X" in pip install? How to downgrade python from 3.7 to 3.6 I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."? Iterating over arrays in Python 3 How to upgrade Python version to 3.7?

Examples related to loops

How to increment a letter N times per iteration and store in an array? Angular 2 Cannot find control with unspecified name attribute on formArrays What is the difference between i = i + 1 and i += 1 in a 'for' loop? Prime numbers between 1 to 100 in C Programming Language Python Loop: List Index Out of Range JavaScript: Difference between .forEach() and .map() Why does using from __future__ import print_function breaks Python2-style print? Creating an array from a text file in Bash Iterate through dictionary values? C# Wait until condition is true

Examples related to dictionary

JS map return object python JSON object must be str, bytes or bytearray, not 'dict Python update a key in dict if it doesn't exist How to update the value of a key in a dictionary in Python? How to map an array of objects in React C# Dictionary get item by index Are dictionaries ordered in Python 3.6+? Split / Explode a column of dictionaries into separate columns with pandas Writing a dictionary to a text file? enumerate() for dictionary in python

Examples related to key-value

Iterate through dictionary values? How can I get key's value from dictionary in Swift? How to add a new object (key-value pair) to an array in javascript? How to search if dictionary value contains certain string with Python Python: How to check if keys exists and retrieve value from Dictionary in descending priority How do you create a dictionary in Java? how to prevent adding duplicate keys to a javascript array How to update value of a key in dictionary in c#? How to create dictionary and add key–value pairs dynamically? How to count frequency of characters in a string?