Python Type Hints: How to Specify Types Inside Lists (list) and Dictionaries (dict)

When defining collection variables like lists (list) or dictionaries (dict) in Python, simply writing items: list is often not enough. Without information like “I know it’s a list, but does it contain numbers or strings?”, there is a risk of errors occurring when processing the extracted elements.

This article explains how to specify the types of contents (element types) for lists and dictionaries in detail.


目次

1. Type Hints for Lists

To specify the type of contents in a list, write it in the format list[ElementType].

Specific Code Example

As an example, let’s define a list managing “temperature data” for a week. Temperature is a decimal (float).

# Notation for Python 3.9 and later
# Explicitly state it's a "list of floats"
daily_temperatures: list[float] = [25.5, 26.0, 24.8, 23.5, 27.2]

# Example of a list of strings
task_list: list[str] = ["Check Email", "Write Report", "Meeting"]

By writing it this way, editors and static analysis tools will warn you if you try to add a string to daily_temperatures or calculate task_list elements as numbers.

Note: For Python 3.8 and earlier From Python 3.9, you can use the standard list as is, but in environments 3.8 and earlier, you need to import List (capitalized) from the typing module.

from typing import List
daily_temperatures: List[float] = [25.5, 26.0]

2. Type Hints for Dictionaries

For dictionaries, you need to specify the types for both keys and values. Write it in the format dict[KeyType, ValueType].

Specific Code Example

Let’s define a cafe’s “Menu Price List” as a dictionary. Keys are menu names (strings) and values are prices (integers).

# Dictionary with str keys and int values
menu_prices: dict[str, int] = {
    "Coffee": 400,
    "Tea": 450,
    "Sandwich": 600
}

# Dictionary with str keys and float values (e.g., Average scores for subjects)
average_scores: dict[str, float] = {
    "Math": 78.5,
    "English": 82.0
}

Note: For Python 3.8 and earlier Similar to lists, use Dict from the typing module for older versions.

from typing import Dict
menu_prices: Dict[str, int] = {"Coffee": 400}

3. Usage in Function Arguments and Return Values

This feature is most useful in function definitions. It clarifies what the list received as an argument contains, making the function implementation safer. As an example, let’s create a function that accepts a list of temperatures and returns the average temperature.

def calculate_average_temp(temperatures: list[float]) -> float:
    """
    Function to accept a list of temperatures and return the average.
    """
    if not temperatures:
        return 0.0
    
    total = sum(temperatures)
    return total / len(temperatures)

# --- Execution ---
week_data = [25.5, 26.0, 24.8]

# Call with correct type
average = calculate_average_temp(week_data)
print(f"Average Temperature: {average:.1f} degrees")

Output:

Average Temperature: 25.4 degrees

If you try to pass a list of strings like calculate_average_temp(["Sunny", "Cloudy"]), you can get a “Type mismatch” warning before execution.


4. Mixing Multiple Types (Union)

If you want to allow multiple types, such as a list containing both integers and strings, use Union (or | in Python 3.10 and later).

from typing import Union

# List containing integers or strings
# Assuming mixed IDs, etc.
mixed_ids: list[Union[int, str]] = [101, "A-202", 305, "B-404"]

# In Python 3.10+, you can write:
# mixed_ids: list[int | str] = [101, "A-202", 305, "B-404"]

Summary

  • Write list type hints as list[int] to clarify the content type.
  • Write dictionary type hints as dict[str, int] to specify key and value types.
  • Using these prevents erroneous operations on collection contents (e.g., calculating a string thinking it’s a number).
  • Use standard list, dict for Python 3.9+, and typing.List, typing.Dict for earlier versions.
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

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

目次