Lecture
Adding and Modifying Elements in a Dictionary
A dictionary manages data through keys, enabling you to add new values or modify existing ones using specific keys.
To add a new key-value pair, use square brackets ([]) with the key and assign a value.
Adding a Value to a Dictionary
user = { "username": "codefriends", "created_at": "2024-01-01" } # Add value "male" to the "gender" key user["gender"] = "male" # Outputs "male" print(user["gender"])
Modifying Dictionary Values
Assigning a new value to an existing key updates the value stored in the dictionary.
Modifying a Value in a Dictionary
user = { "username": "codefriends", "created_at": "2024-01-01" } user["username"] = "geekhaus" # Outputs "geekhaus" print(user["username"])
Previous lessonUtilizing Values Within a DictionaryNext lessonRemoving a Specific Element from a Dictionary
Lessons in this chapter · Dictionary and Set Data Types for Managing Structured Data
- 1. Managing Structured Data with Dictionaries
- 2. Utilizing Values Within a Dictionary
- 3. Adding and Modifying Elements in a Dictionary
- 4. Removing a Specific Element from a Dictionary
- 5. Multiple-choice quiz
- 6. Handling Dictionary KeyError Exceptions
- 7. Checking Key Existence in a Dictionary
- 8. Safely Checking for Key Existence in a Dictionary
- 9. Multiple-choice quiz
- 10. Set Data Type that Does Not Allow Duplicate Values
- 11. Intersection, Union, Difference Operations
- 12. Adding Elements to a Set
- 13. Removing Elements from a Set
- 14. Utilizing Values within a Set
- 15. Differences Between Shallow and Deep Copy
- 16. Coding Quiz - Safely Extract Values from a Dictionary
- 17. Multiple-choice quiz
- 18. Fill-in-the-blank quiz
Quiz
0 / 1
What is the correct way to add a new key-value pair to a dictionary?
Delete the dictionary's key and add a new key.
Copy the dictionary and add a new key.
Use square brackets [] to specify the key and assign the value.
You cannot add a new key to a dictionary.
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help