Flat_Eric On the phone wearing a red shirt

More Methods

Membership and View Methods

Now that we can safely retrieve data, we need ways to inspect the dictionary as a whole—checking if keys exist and pulling out lists of all labels or data.

The in Operator (Membership Testing)

The in operator is the fastest and most readable way to check if a key exists in a dictionary before you try to use it. It returns a Boolean value: True or False. The "in" operator only checks keys, not values.

Viewing Dictionary Data

Sometimes you need to look at the dictionary's contents without targeting a specific key. Python provides three "view" methods for this:

  1. .keys()This method returns a view of all the keys in the dictionary. It is useful when you need a list of all the labels or identifiers available.
    • Use the .keys method to see the keys.
  2. .values()This method returns a view of all the values (the data) stored in the dictionary, ignoring the keys entirely.
    • Use the .values method to see the values.
  3. .items()This is one of the most powerful methods. It returns each key-value pair as a tuple. This is the standard way to look at everything inside the dictionary at once.
    • Use the .items method to see the items.

Why use these?

These "view" objects are dynamic. If the dictionary changes, the view updates automatically. They are most commonly used in loops (which we will cover soon) to iterate through data.

A Note on .items() and Tuples

When you use the .items() method, Python gives you back the dictionary's data in pairs. If you look closely at the output, you’ll notice these pairs are wrapped in parentheses () rather than square brackets [].

These small groups inside the parentheses are called Tuples.

Time to experiment!

Coding Exercises (VS Code) Instructions:

Exercise 1: Membership Check

Use the in operator to verify if a specific key is present.

Exercise 2: Documentation Discovery

Part of being a coder is learning to read documentation.

Exercise 3: Data Dump

Extract just the values from a dictionary.

Exercise 4: Pairing Up

View the full relationship between keys and values and notice the tuples.

Exercise 5: Number Keys and Membership

Confirm that in works with integer keys as well.

Don't Forget to commit and Push!

This course was built by DevSTEM - we turn teaching materials into interactive web courses like this one.

Build your own course
>