Dictionaries: Keys and Values
In Python, a dictionary is like a real-life dictionary: you look up a key (word) to get a value (definition).
But in programming, keys can be strings, numbers, or even tuples — and values can be anything.
Why Use Dictionaries?
Unlike lists, where you access items by position, dictionaries let you access data by name.
This makes your code easier to understand, especially when dealing with labeled data.
For example:
student = { "name": "Emily", "age": 22, "major": "Biology" }
Here, instead of guessing what index 2
means, you simply write student["major"]
.
Key Concepts
- Each item in a dictionary is a pair: a key and a value.
- Keys must be unique and immutable.
- Values can be anything — numbers, strings, lists, or even other dictionaries.
- Use
dict[key]
to retrieve or change a value.
When Are Dictionaries Useful?
Dictionaries are especially useful when your data has labels — like user profiles, settings, or grouped information.
They’re also essential for JSON-like data structures and working with APIs.
Next, you’ll practice how to work with dictionary methods and nesting.
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result