Finding and Adding Items in Dictionaries
Dictionaries are super useful when you want to store and quickly retrieve data using keys. Let’s look at how to find information and add new items dynamically.
Finding Items
To check if a key exists in a dictionary, use the in
keyword:
student = {"name": "Kwame", "age": 22}
if "age" in student:
print("Yes, age is one of the keys.")
You can also check for values using the .values()
method:
if 22 in student.values():
print("Yes, 22 is one of the values.")
Adding New Items
To add a new key-value pair, just assign it directly:
student["grade"] = "A"
This creates the "grade"
key if it doesn't exist, or updates it if it does.
Using Loops to Add Multiple Items
You can build a dictionary from a list or while iterating:
names = ["Ama", "Yaw", "Kojo"]
ages = [19, 21, 22]
students = {}
for i in range(len(names)):
students[names[i]] = ages[i]
print(students)
Output
{'Ama': 19, 'Yaw': 21, 'Kojo': 22}
Using the .setdefault()
Method
The setdefault()
method adds a key only if it doesn’t exist:
profile = {"username": "init_user"}
profile.setdefault("email", "not_provided@example.com")
Exercise: Try It Yourself!
- Create a dictionary named book with keys
"title"
and"author"
. - Use
in
to check if"publisher"
exists. - Add
"year"
with a value of2022
. - Use a loop to add 3 new keys:
"pages"
,"genre"
,"language"