Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python - Updating value list in dictionary
In Python, dictionaries store data as key-value pairs where values can be lists. Updating these value lists is a common operation when working with dynamic data structures.
Syntax
dictionary_name[key] = new_value_list
You can update a value list by assigning a new list to the specific key using the assignment operator (=). This replaces the existing list associated with that key.
Method 1: Direct Assignment
Replace the entire value list with a new list ?
# Create a dictionary with initial values
student_grades = {
'math': [85, 90, 78],
'science': [92, 88, 95]
}
# Update the value list for 'math' key
student_grades['math'] = [85, 90, 78, 96]
print(student_grades)
{'math': [85, 90, 78, 96], 'science': [92, 88, 95]}
Method 2: Modifying Existing Lists
Append, extend, or modify the existing list without replacing it ?
# Create a dictionary with initial values
courses = {
'python': ['basics', 'advanced'],
'java': ['oop', 'swing'],
'web': ['html', 'css']
}
# Append to existing lists
courses['python'].append('django')
courses['java'].extend(['jdbc', 'spring'])
# Modify specific elements
courses['web'][0] = 'html5'
print(courses)
{'python': ['basics', 'advanced', 'django'], 'java': ['oop', 'swing', 'jdbc', 'spring'], 'web': ['html5', 'css']}
Method 3: Updating Multiple Keys
Update value lists for multiple keys using a loop ?
# Create a dictionary with course information
subjects = {
'math': ['algebra', 'geometry'],
'science': ['physics', 'chemistry'],
'language': ['english', 'spanish']
}
# Add 'advanced' to all subjects
for key in subjects:
subjects[key].append('advanced')
print(subjects)
{'math': ['algebra', 'geometry', 'advanced'], 'science': ['physics', 'chemistry', 'advanced'], 'language': ['english', 'spanish', 'advanced']}
Comparison
| Method | Operation | Best For |
|---|---|---|
| Direct Assignment | Replaces entire list | Complete list replacement |
| append() | Adds single item | Adding one element |
| extend() | Adds multiple items | Adding multiple elements |
| Index modification | Changes specific element | Updating particular values |
Conclusion
Use direct assignment to replace entire lists, or methods like append() and extend() to modify existing lists. Choose the approach based on whether you need complete replacement or incremental updates to your dictionary value lists.
