0
0
Pythonprogramming~5 mins

Dictionary iteration in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is dictionary iteration in Python?
Dictionary iteration means going through each key or value in a dictionary one by one to use or check them.
Click to reveal answer
beginner
How do you iterate over keys in a Python dictionary?
Use a for loop directly on the dictionary, like for key in my_dict:. This loops over all keys.
Click to reveal answer
beginner
How can you get both keys and values when iterating a dictionary?
Use for key, value in my_dict.items(): to get each key and its value together.
Click to reveal answer
beginner
What does my_dict.values() do in dictionary iteration?
It gives you all the values in the dictionary, so you can loop over just the values without keys.
Click to reveal answer
beginner
Why is dictionary iteration useful in programming?
It helps you check, change, or use each piece of data stored in the dictionary easily, like looking up phone numbers or settings.
Click to reveal answer
Which method lets you loop over both keys and values in a dictionary?
Aitems()
Bkeys()
Cvalues()
Dall()
What does this code print?
my_dict = {'a':1, 'b':2}
for key in my_dict:
print(key)
A1 and 2
BNothing
C'a' and 'b'
DError
How do you loop over only the values in a dictionary?
Afor val in my_dict.keys():
Bfor val in my_dict.values():
Cfor val in my_dict.items():
Dfor val in my_dict:
What type of object does my_dict.items() return?
AString
BList of values
CList of keys
DView of key-value pairs
Which of these is NOT a way to iterate a dictionary?
Afor i in range(my_dict):
Bfor key in my_dict:
Cfor val in my_dict.values():
Dfor key, val in my_dict.items():
Explain how to loop through a dictionary to get both keys and values.
Think about the method that returns pairs.
You got /3 concepts.
    Why might you want to iterate over just the keys or just the values in a dictionary?
    Consider what you need from the dictionary.
    You got /3 concepts.