Dictionaries: Keys and Values
In Python, a dictionary is a collection of key-value pairs that maps one item (the key) to another (the value).
In the example below, the keys represent fruits, and the values represent their corresponding 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, which access items by position, dictionaries retrieve data using keys.
This makes your code easier to read and maintain, especially when working with labeled information.
For instance, if you want to store details about 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 particularly useful when working with labeled data, such as user profiles, configuration settings, or grouped information.
They are also essential for handling JSON-like data and API responses.
Lessons in this chapter ยท Python Programming Review
- 1. Variables and Data Types
- 2. Expressions and Arithmetic
- 3. String Operations
- 4. Lists in Python
- 5. List Methods and Slicing
- 6. Tuples and Sets
- 7. Dictionaries - Keys and Values
- 8. Dictionary Methods and Nesting
- 9. Conditional Statements (if, elif, else)
- 10. Loops - for and while
- 11. Control Flow & Data Structures Recap
- 12. Multiple-choice quiz
- 13. Loop Controls (break, continue, pass)
- 14. Functions - Defining and Calling
- 15. Function Arguments and Return Values
- 16. Variable Scope and Nested Functions
- 17. Exception Handling with try/except
- 18. File Reading and Writing
- 19. CSV File Parsing
- 20. Using Built-in Modules (math, random, datetime)
- 21. Importing External Modules
- 22. Fill-in-the-blank quiz
In Python dictionaries, keys must be unique and immutable.
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help