The items() method returns key-value pairs as tuples.
Step 2: Convert items to list
Using list() converts these pairs into a list of tuples: [('a', 1), ('b', 2)].
Final Answer:
[('a', 1), ('b', 2)] -> Option A
Quick Check:
items() = list of (key, value) pairs [OK]
Hint: items() returns pairs; list() shows them as list of tuples [OK]
Common Mistakes:
Thinking items() returns only keys or only values
Expecting a dictionary instead of list of tuples
Confusing items() with keys() or values()
4. Find the error in this code snippet:
my_dict = {'x': 10, 'y': 20}
for key, value in my_dict.keys():
print(key, value)
medium
A. Syntax error in for loop
B. keys() returns only keys, cannot unpack into two variables
C. Missing parentheses after print
D. No error, code runs fine
Solution
Step 1: Check what keys() returns
keys() returns only keys, so each item is a single value, not a pair.
Step 2: Understand unpacking in for loop
The loop tries to unpack each key into two variables, causing an error.
Final Answer:
keys() returns only keys, cannot unpack into two variables -> Option B
Quick Check:
keys() = keys only, no pairs [OK]
Hint: keys() gives one value per item; items() gives pairs [OK]
Common Mistakes:
Trying to unpack keys() into two variables
Confusing keys() with items()
Assuming keys() returns key-value pairs
5. You have a dictionary grades = {'Alice': 85, 'Bob': 92, 'Charlie': 78}. Which code snippet correctly prints each student's name and grade using dictionary methods?
hard
A. for name, grade in grades.values():
print(name, grade)
B. for name, grade in grades.keys():
print(name, grade)
C. for name, grade in grades.items():
print(name, grade)
D. for grade in grades.values():
print(grade)
Solution
Step 1: Identify method to get pairs
items() returns key-value pairs, perfect for name and grade.
Step 2: Check each option
for name, grade in grades.values():
print(name, grade) unpacks grades.values() (single values): error. for name, grade in grades.keys():
print(name, grade) unpacks grades.keys() (single keys): error. for grade in grades.values():
print(grade) prints only grades. for name, grade in grades.items():
print(name, grade) correctly unpacks grades.items() pairs.
Final Answer:
for name, grade in grades.items(): print(name, grade) -> Option C
Quick Check:
items() gives key-value pairs for easy unpacking [OK]
Hint: Use items() to loop over keys and values together [OK]