Which method returns both keys and values during iteration?
Analysis & Theory
`items()` returns key-value pairs that can be looped over using `for key, value in dict.items()`.
What will this code print?
d = {'a': 1, 'b': 2}
for key in d:
print(key)
Analysis & Theory
Looping through a dictionary by default iterates over the keys.
Which method would you use to loop through only the values of a dictionary?
Analysis & Theory
`values()` returns all the values in the dictionary.
What is the correct syntax to loop over key-value pairs in a dictionary?
A
for key in dict.items():
B
for key, value in dict.items():
C
for item in dict.get():
D
for key -> value in dict:
Analysis & Theory
`for key, value in dict.items()` is the correct way to loop over key-value pairs.
What is the output of:
d = {'x': 10, 'y': 20}
for v in d.values():
print(v)
Analysis & Theory
`values()` returns just the values: `10` and `20`.
What will this code print?
d = {'a': 1, 'b': 2}
for k, v in d.items():
print(k + str(v))
Analysis & Theory
Each key is concatenated with its stringified value, printing `'a1'` and `'b2'`.
What does the `keys()` method return?
A
List of key-value pairs
B
View object of dictionary keys
Analysis & Theory
`keys()` returns a view object containing the dictionary’s keys.
What will `list(dict.items())` return?
C
List of key-value tuples
Analysis & Theory
`dict.items()` returns a view of key-value pairs, and converting it to a list creates a list of tuples.
Can you use `enumerate()` with a dictionary directly?
A
Yes, it enumerates over key-value pairs
B
Yes, it enumerates over the dictionary keys
D
Only with `dict.items()`
Analysis & Theory
`enumerate(dict)` gives index and key, since looping over a dictionary gives keys.
Which loop correctly prints all key-value pairs from a dictionary `data`?
A
for k, v in data: print(k, v)
B
for k in data: print(k, data[k])
C
for k in data.values(): print(k)
D
for v in data.items(): print(v)
Analysis & Theory
`for k in data` loops over keys, and `data[k]` accesses their corresponding values.