Practice: Introduction to Dictionaries
Q1. Build a profile
Create a dictionary named `person` with keys name ("Ravi") and age (20), then print it.
Goal: Create a dictionary.
Q2. Read one value
Given `car = {"brand": "Tata", "year": 2020}`, print only the brand.
Goal: Read a value by key.
Q3. Add a pair
Start with `d = {"a": 1}`. Add the key b with value 2 and print the dictionary.
Goal: Add entries.
Q4. Count the pairs
Print how many pairs are in `{"x": 1, "y": 2, "z": 3}`.
Goal: Use len with a dict.
Q5. Safe lookup
Given `stock = {"pen": 5}`, print the stock of "ink", showing 0 if it is missing.
Goal: Use get with a default.
Q6. Sum the values
Print the total of all values in `{"a": 10, "b": 20, "c": 30}`.
Goal: Loop and aggregate values.
Q7. Print each pair
Print every pair of `{"x": 1, "y": 2}` as `x = 1` on its own line.
Goal: Loop with items().
Q8. Index words by length
Make a dictionary from the list ["hi", "python", "code"] where each word maps to its length. Print it.
Goal: Build a dictionary in a loop.
Q9. What is printed? 1
Predict the output.
d = {"a": 1, "b": 2}
d["a"] = 10
print(d)Goal: Update values.
Q10. What is printed? 2
Predict the output.
d = {"a": 1, "a": 2}
print(d)
print(len(d))Goal: Keys are unique.
Q11. What is printed? 3
Predict the output.
d = {"x": 5}
print("x" in d, 5 in d)Goal: Membership test.
Q12. What is printed? 4
Predict the output.
d = {"a": 1, "b": 2}
print(d.get("c"))
print(d.get("c", "none"))Goal: get() behaviour.
Q13. What is printed? 5
Predict the output.
d = {"a": 1, "b": 2, "c": 3}
d.pop("b")
print(list(d))Goal: Delete entries.
Q14. What is printed? 6
Predict the output.
d = dict.fromkeys("abc", 0)
d["b"] += 1
print(d)Goal: fromkeys.
Q15. Fix the KeyError
This code crashes. Fix it so it prints 0 for the missing key.
d = {"a": 1}
print(d["b"])Goal: Avoid KeyError.
Q16. Fix the bad key
This code raises TypeError. Fix it so it prints home.
places = {[1, 2]: "home"}
print(places[[1, 2]])Goal: Hashable keys.
Q17. Fix the loop
The loop below tries to remove zero-valued keys and crashes. Fix it.
d = {"a": 0, "b": 1, "c": 0}
for k in d:
if d[k] == 0:
del d[k]
print(d)Goal: Safe deletion.
Q18. Key or value?
Does `3 in {"a": 3}` return True or False? Explain.
Goal: Membership.
Q19. Allowed keys
Why can a tuple be a dictionary key but a list cannot?
Goal: Hashability.
Q20. Choose the structure
A shop needs to find a price from a product name. Would you use a list or a dictionary and why?
Goal: Choose a data structure.