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()
- Creating Dictionaries: {} vs dict()
- 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 :.
- The .get() Method: Your Safety Net
- 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.
We have already seen the most common way to create a dictionary using curly braces, but Python also offers the dict() constructor.
The .get() method is one of the most important tools in your dictionary toolkit because it prevents your program from crashing.
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:
- Create a file named methods.py in your part30 folder.
- Complete the tasks and use # comments to explain your answers.
Exercise 1: Creating with dict()
Practice using the function syntax to build a dictionary.
-
Task: Create a dictionary named
laptopusing thedict()function. Give it two keys:brand(set to "Apple") andyear(set to 2022). - Goal: Print the dictionary to see how Python converts the keyword arguments into a standard dictionary.
Exercise 2: The Safe Search
Use .get() to avoid the dreaded KeyError.
-
Starting Code:
hero = {"name": "Peter Parker", "alias": "Spider-Man"} -
Task: Use the
.get()method to look for a key named"power". -
Goal: Print the result and verify that it returns
Noneinstead of crashing your program.
Exercise 3: Providing a Backup
Sometimes "None" isn't helpful enough. Practice providing a default value.
-
Starting Code:
settings = {"volume": 80, "brightness": 50} -
Task: Use
.get()to look for"language". If it doesn't exist, have it return the string"English". - Goal: Print the result to ensure your "backup" value appears.
Exercise 4: dict() vs Curly Braces
Compare the two creation methods side-by-side.
-
Task: Create the exact same dictionary—
{"a": 1, "b": 2}—twice. First, name itmethod_oneusing curly braces. Second, name itmethod_twousing thedict()function. -
Goal: Print
method_one == method_two. It should returnTrue!
Exercise 5: Real-world Logic
Simulate a simple database check.
-
Task: Create a dictionary
inventory = {"apples": 50}. Prompt the user (or just hardcode a variable) to look for"oranges". -
Goal: Use
.get()so that if the item isn't in stock, it prints0instead of throwing an error.
Don't Forget to commit and Push!