Adding and Modifying Elements in a Dictionary
A dictionary manages data through keys
, allowing you to add new values or modify existing ones using specific keys.
To add a new key-value pair, input the key within square brackets ([]
) and assign it 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 modifies that keyβs current value.
Modifying a Value in a Dictionary
user = { "username": "codefriends", "created_at": "2024-01-01" } user["username"] = "geekhaus" # Outputs "geekhaus" print(user["username"])
Mission
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.
Guidelines
AI Tutor
Publish
Design
Upload
Notes
Favorites
Help
Code Editor
Run
Generate
Execution Result