5 4 Dictionaries Explained
Key Concepts
Dictionaries in Python are unordered collections of key-value pairs. The key concepts include:
- Creating Dictionaries
- Accessing Values
- Modifying Dictionaries
- Dictionary Methods
- Dictionary Comprehensions
1. Creating Dictionaries
Dictionaries are created using curly braces {}
with key-value pairs separated by colons. Each key-value pair is separated by a comma.
Example:
student_scores = { "Alice": 90, "Bob": 85, "Charlie": 92 }
2. Accessing Values
Values in a dictionary are accessed using their keys. This can be done using square brackets []
with the key inside.
Example:
student_scores = { "Alice": 90, "Bob": 85, "Charlie": 92 } print(student_scores["Alice"]) # Output: 90
Analogy: Think of a dictionary as a phone book where each name (key) has a corresponding phone number (value).
3. Modifying Dictionaries
Dictionaries are mutable, meaning you can change their content. You can add new key-value pairs, update existing values, or remove key-value pairs.
Example:
student_scores = { "Alice": 90, "Bob": 85, "Charlie": 92 } student_scores["Alice"] = 95 student_scores["David"] = 88 del student_scores["Bob"] print(student_scores) # Output: {'Alice': 95, 'Charlie': 92, 'David': 88}
4. Dictionary Methods
Python provides several built-in methods to manipulate dictionaries. Some common methods include keys()
, values()
, items()
, and get()
.
Example:
student_scores = { "Alice": 90, "Bob": 85, "Charlie": 92 } print(student_scores.keys()) # Output: dict_keys(['Alice', 'Bob', 'Charlie']) print(student_scores.values()) # Output: dict_values([90, 85, 92]) print(student_scores.items()) # Output: dict_items([('Alice', 90), ('Bob', 85), ('Charlie', 92)]) print(student_scores.get("Alice")) # Output: 90
5. Dictionary Comprehensions
Dictionary comprehensions provide a concise way to create dictionaries. They are often used to apply an expression to each item in an existing iterable.
Example:
squares = {x: x**2 for x in range(5)} print(squares) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Putting It All Together
By understanding and using dictionaries effectively, you can store and manipulate collections of key-value pairs in Python. Dictionaries are a fundamental data structure that you will use frequently in your programming journey.
Example:
student_scores = { "Alice": 90, "Bob": 85, "Charlie": 92 } student_scores["Alice"] = 95 student_scores["David"] = 88 del student_scores["Bob"] print(student_scores.keys()) # Output: dict_keys(['Alice', 'Charlie', 'David']) print(student_scores.values()) # Output: dict_values([95, 92, 88]) print(student_scores.items()) # Output: dict_items([('Alice', 95), ('Charlie', 92), ('David', 88)]) squares = {x: x**2 for x in range(5)} print(squares) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}