Dictionaries: Keys and Values
In Python, a dictionary is a collection of key-value pairs.
In the example below, the keys are the fruits and the values are the numbers.
my_dict = { "apple": 1, "banana": 2, "cherry": 3 }
Dictionaries are useful when you need to store and retrieve data by a specific key.
Why Use Dictionaries?
Unlike lists, where you access items by position, dictionaries let you access data by key.
This makes your code easier to understand, especially when dealing with labeled data.
For example, if you want to store the information of a student, you can use a dictionary like this:
student = { "name": "Emily", "age": 22, "major": "Biology" }
In the example above, to retrieve the student's name, you would use student["name"]
.
Key Concepts
- Each item in a dictionary is a pair of a key and a value.
- Keys must be unique and immutable.
- Values can be any type: numbers, strings, lists, or even other dictionaries.
- Use
dict[key]
to retrieve or update a value.
When Are Dictionaries Useful?
Dictionaries are especially useful when your data has labels, such as user profiles, settings, or grouped information.
They are also essential for working with JSON-like data structures and APIs.
In Python dictionaries, keys must be unique and immutable.
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result