Create a dictionary for a student's info (name: value, age: value). Print the whole dict and access specific values. (Concepts: dictionaries, key-value pairs, accessing values)
student = {"name": "Alex", "age": 20, "grade": "A"}
print("Student info:", student)
print("Name:", student["name"])
print("Age:", student["age"])Day 17: Dictionaries—key-value stores like labeled boxes! student = {"name": "Alex", "age": 20, "grade": "A"}—curly braces, keys (strings) colon values (mixed types). Keys are unique; values can duplicate.
Print the whole: Shows {'name': 'Alex', ...}. Access with student["name"]—key in brackets, like list indexing but by label, not position. Safe if key exists; errors otherwise. Run: Full dict, then Name: Alex, Age: 20.
In 10-15 min, add a key like "city" and access it. Dicts are unordered but fast for lookups—great for configs or user data, unlike lists' order focus. Expanding collections!
Key Concepts:
- Dictionary: Mutable collection of key-value pairs in curly braces {}, where keys are unique and hashable (e.g., strings), values can be anything.
- Key-Value Pair: Format in dicts: key: value (e.g., "name": "Alex").
- Accessing Values: Retrieve with square brackets and key (e.g., dict["key"]).