Iterate through dictionary values? Iterate through dictionary values? python-3.x python-3.x

Iterate through dictionary values?


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/


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