Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
Loading…
Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
Loading…
Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
PYTHON DATA / CHAPTER 02 / Learn / LESSON 02
Second Data class. A list stores a sequence. A person’s profile, though, has named fields: age, height, weight — not “first, second, third”.
A dictionary (dict) maps key → value. Keys are usually quoted strings. The syntax uses curly braces {}:
profile = {"age": 25, "height": 1.8, "weight": 75.0}Reading uses square brackets and the key: profile["age"] → 25. This is not a list index — you ask by name. If you mistype the key (for example "Age" with a capital letter), Python looks for a different field and raises KeyError.
Mini example:
person = {"name": "Ada", "year": 1815}
print(person["name"])
print(person["year"])Why a dict instead of three separate variables? Because the profile is one object: later you pass it to functions, add keys, serialize it. Today we only create and read.
Common mistake: writing profile["age"] as profile.age (a different style, not for this lesson); keys without quotes; mixing list and dict brackets.
Learn: you write the dict and the print lines.
PROFILE IDLE
›