We are thrilled to inform you that Lancecourse is becoming INIT Academy — this aligns our name with our next goals — Read more.

It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for lancecourse.com.

Python Basics

Course by zooboole,

Last Updated on 2025-02-26 16:14:49

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!

  1. Create a dictionary named book with keys "title" and "author".
  2. Use in to check if "publisher" exists.
  3. Add "year" with a value of 2022.
  4. Use a loop to add 3 new keys:
    • "pages", "genre", "language"