Flat_Eric Talking in the phone wearing a blue shirt

Methods

What is a Dictionary Method?

A method is essentially a built-in function that "belongs" to a specific object. In Python, because a dictionary is an object, it comes with its own set of specialized tools (methods) designed to handle tasks like searching, updating, or cleaning up data.

You can think of a dictionary like a smart filing cabinet. While you can manually open a drawer to grab a folder, a method is like pressing a button on the cabinet to perform a specific action—like "find this folder safely" or "list all the labels on these drawers."

In Python, you call these methods by using a dot . after the name of your dictionary:

dictionary_name.method_num()

  1. Creating Dictionaries: {} vs dict()
  2. We have already seen the most common way to create a dictionary using curly braces, but Python also offers the dict() constructor.

    • The Literal Way (Curly Braces): user = {"name": "Alex", "age": 20} This is the industry standard. It is faster for the computer to read and very easy for humans to see the "key to value" connection.
    • The Function Way (dict()): user = dict(name="Alex", age=20) This looks like a standard Python function. Notice that when using this method, you don't put quotes around the keys, and you use an equals sign = instead of a colon :.
  3. The .get() Method: Your Safety Net
  4. The .get() method is one of the most important tools in your dictionary toolkit because it prevents your program from crashing.

    • The Problem: Using my_dict["key"] on a key that doesn't exist triggers a KeyError and stops your code entirely.
    • The Solution: .get() checks if the key exists first. If it finds it, it returns the value. If it doesn't find it, it returns None instead of an error.

Test Your Knowledge

Select the correct answer below to see if you've mastered Python dictionaries and the .get() method.

Loading quiz...

Time to experiment!

Coding Exercises (VS Code) Instructions:

Exercise 1: Creating with dict()

Practice using the function syntax to build a dictionary.

Exercise 2: The Safe Search

Use .get() to avoid the dreaded KeyError.

Exercise 3: Providing a Backup

Sometimes "None" isn't helpful enough. Practice providing a default value.

Exercise 4: dict() vs Curly Braces

Compare the two creation methods side-by-side.

Exercise 5: Real-world Logic

Simulate a simple database check.

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