Lesson 22 of 4055%
(Progress persistence is disabled until Phase 9)
Python
Beginner
Dictionaries
Store data in key-value pairs.
Dictionaries
What You’ll Learn
You’ll learn how to use dictionaries to map keys to values, similar to objects in JavaScript.
What is a Dictionary?
Dictionaries are used to store data values in key:value pairs. They are written with curly brackets {}, and have keys and values.
user = {
"name": "John",
"age": 30,
"role": "Admin"
}
print(user)
Accessing Items
You can access the items of a dictionary by referring to its key name, inside square brackets.
print(user["name"]) # John
Or use the .get() method, which is safer because it returns None (instead of throwing an error) if the key doesn’t exist:
print(user.get("age")) # 30
print(user.get("email")) # None
Changing and Adding Items
You can change the value of a specific item by referring to its key name. If the key doesn’t exist, it will be added.
# Update existing
user["age"] = 31
# Add new
user["email"] = "john@example.com"