5 4 2 Dictionary Methods Explained
Key Concepts
Dictionary methods in Python allow you to manipulate dictionaries, which are collections of key-value pairs. The key concepts include:
- Adding and Updating Elements
- Removing Elements
- Accessing Elements
- Dictionary Methods
1. Adding and Updating Elements
You can add new key-value pairs to a dictionary using assignment. If the key already exists, its value will be updated.
Example:
student = {"name": "Alice", "age": 25} student["major"] = "Computer Science" print(student) # Output: {'name': 'Alice', 'age': 25, 'major': 'Computer Science'} student["age"] = 26 print(student) # Output: {'name': 'Alice', 'age': 26, 'major': 'Computer Science'}
2. Removing Elements
Elements can be removed from a dictionary using the pop()
method, which removes the item with the specified key, or the clear()
method, which removes all items.
Example:
student = {"name": "Alice", "age": 25, "major": "Computer Science"} age = student.pop("age") print(age) # Output: 25 print(student) # Output: {'name': 'Alice', 'major': 'Computer Science'} student.clear() print(student) # Output: {}
3. Accessing Elements
You can access the value associated with a specific key using square brackets []
or the get()
method. The get()
method allows you to provide a default value if the key does not exist.
Example:
student = {"name": "Alice", "age": 25, "major": "Computer Science"} name = student["name"] print(name) # Output: Alice age = student.get("age", "Unknown") print(age) # Output: 25 gpa = student.get("gpa", "Unknown") print(gpa) # Output: Unknown
4. Dictionary Methods
Python provides several built-in methods to manipulate dictionaries. Some common methods include keys()
, values()
, items()
, and update()
.
Example:
student = {"name": "Alice", "age": 25, "major": "Computer Science"} keys = student.keys() print(keys) # Output: dict_keys(['name', 'age', 'major']) values = student.values() print(values) # Output: dict_values(['Alice', 25, 'Computer Science']) items = student.items() print(items) # Output: dict_items([('name', 'Alice'), ('age', 25), ('major', 'Computer Science')]) student.update({"gpa": 3.8}) print(student) # Output: {'name': 'Alice', 'age': 25, 'major': 'Computer Science', 'gpa': 3.8}
Putting It All Together
By understanding and using dictionary methods effectively, you can efficiently manage and manipulate key-value pairs in Python.
Example:
student = {"name": "Alice", "age": 25} student["major"] = "Computer Science" student["age"] = 26 age = student.pop("age") print(age) # Output: 26 name = student["name"] print(name) # Output: Alice gpa = student.get("gpa", "Unknown") print(gpa) # Output: Unknown student.update({"gpa": 3.8}) print(student) # Output: {'name': 'Alice', 'major': 'Computer Science', 'gpa': 3.8}