Skip to main content
Practice

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, input the key within a square bracket ([]) 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 the value associated with that key.

Modifying a Value in a Dictionary
user = {
"username": "codefriends",
"created_at": "2024-01-01"
}

user["username"] = "geekhaus"
# Outputs "geekhaus"
print(user["username"])

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.