Lesson · Python for Beginners
Dictionaries and key-value data
A dictionary connects keys to values, which is useful when positions would be hard to remember.
What you will learn
- Create a dictionary
- Read and update a key
- Use get for optional keys
Look up by meaning
A dictionary stores key-value pairs inside braces. A key such as 'name' expresses what its value represents, unlike a list index whose meaning depends on position. Keys must be unique and hashable; strings are a common choice. Values can be different kinds of data, including lists or other dictionaries.
Read and change entries
Square brackets retrieve a value for a known key, but a missing key raises KeyError. Use get when a key may be absent and a default is appropriate. Assigning to an existing key replaces its value; assigning to a new key adds an entry.
Process fields intentionally
A record-like dictionary can describe one learner, product, or setting. Read only the fields your operation needs, and choose names that make their meaning clear. Avoid depending on an accidental display order when the relationship between a key and its value is the important part.
Iterate over pairs
The items method yields key-value pairs, which a for loop can unpack into two names. This is useful for printing a summary or applying a transformation to every field. If a program requires a predictable display order, choose and document that order rather than assuming a particular arrangement.
Membership checks the keys
Use the in operator to ask whether a dictionary contains a key. It does not search through every value. This distinction matters when a record contains the same text in an unrelated field. Use get when a default is meaningful, but avoid a default that makes missing data look like a valid fact.
course = {'name': 'Python', 'lessons': 12}
course['lessons'] += 1
print(course.get('name'))
print(course['lessons'])
Expected output
Python
13
Practice exercise
Create a dictionary for a book with title and pages, then print a sentence using both values.
Show a hint
Read each value by its key.
Show one possible solution
book = {'title': 'Small Steps', 'pages': 120}; print(f"{book['title']} has {book['pages']} pages.") prints a sentence from the record.
Quick check
Use get or check membership when a key might not exist.