Adding Logic on Top of Data Structures
After the basic dictionary problems, I solved problems that combine dictionaries with conditionals and loops. I felt it directly: a data structure is just a container for data, and control flow is what makes the container useful.
Dictionaries Meet if
I wrote logic that stores items as {name: price} and returns the price for a name the user types. I added a condition to stop execution when the item doesn't exist.
store = {"apple": 1000, "banana": 1500}
name = input("Item name: ")
if name in store:
print(f"The price of {name} is {store[name]}.")
else:
print("We don't sell that item.")Getting into the habit of checking key existence with the in operator first was the key.
Working with Nested Structures
- Putting a list as a dictionary value to extend an item list
- Putting another dictionary as a value to represent a per-student subject/score table
- Iterating nested structures with
for key, value in dict.items():to pull out only what I need
Takeaway
Key point
For the same problem I wrote option 1, option 2, and a final answer, practicing to refine toward "shorter, more readable." The combination of dictionaries, loops, and conditionals carried straight into my later data-collection code for parsing and filtering JSON responses from APIs.