Getting Values from Python Dictionaries: Using [] vs .get()

To use data stored in a Python dictionary (dict), you need to retrieve the “Value” by specifying the corresponding “Key”. There are two main ways to do this: the basic method using square brackets [], and the safer method using the .get() method.

This article explains the differences between these two methods and how to choose the right one to avoid errors (KeyError).


目次

1. Accessing Values with Square Brackets []

You can retrieve a value by writing ["key_name"] after the dictionary variable. This is the most common and intuitive method.

Syntax:

value = dict_variable["key"]

Example: Let’s look at a dictionary managing product information.

# Product Data Dictionary
product_data = {
    "id": "P-1024",
    "name": "Wireless Mouse",
    "price": 2980
}

# Get values by specifying keys
product_name = product_data["name"]
product_price = product_data["price"]

print(f"Product Name: {product_name}")
print(f"Price: {product_price}")

Output:

Product Name: Wireless Mouse
Price: 2980

Specifying a Non-Existent Key (KeyError)

The caveat with this method is that if you specify a key that does not exist in the dictionary, the program will stop with an error (KeyError).

# Trying to access the non-existent key "color"
# color = product_data["color"]
# KeyError: 'color'

Unless you are certain the key exists, you should consider using the .get() method introduced next or handle the exception with a try-except block.


2. Accessing Values with the .get() Method

Using the .get() method allows you to retrieve values safely without causing an error, even if the key does not exist.

Syntax:

value = dict_variable.get("key", default_value)

When the Key Exists

Just like using [], the corresponding value is returned.

# Key "id" exists, so its value is returned
product_id = product_data.get("id")
print(f"Product ID: {product_id}")

Output:

Product ID: P-1024

When the Key Does Not Exist (Default Behavior)

This is the biggest difference. If the key does not exist, no error occurs. Instead, None (an object representing no value) is returned.

# Accessing the non-existent key "stock"
stock_count = product_data.get("stock")

print(f"Stock Count: {stock_count}")

Output:

Stock Count: None

When the Key Does Not Exist (Specifying a Default Value)

By specifying a value as the second argument to .get(), you can set a “default value” to return if the key is not found.

# If "category" key is missing, return "Uncategorized"
category = product_data.get("category", "Uncategorized")

print(f"Category: {category}")

# "price" key exists, so 2980 is returned (default value 0 is ignored)
price_check = product_data.get("price", 0)

print(f"Price Check: {price_check}")

Output:

Category: Uncategorized
Price Check: 2980

Summary

Choose the method based on the situation when retrieving values from a dictionary.

  • dict["key"]: Use when you are certain the key exists. Raises KeyError if missing.
  • dict.get("key"): Use when the key might not exist. Returns None, preventing the program from crashing.
  • dict.get("key", default): Useful when you want to use a specific value (like 0 or an empty string) if the key is missing.
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次