Skip to content
Home / Fundamentals

Python Typing Concrete Collections

In Python's typing module, there are several types that correspond to built-in types (such as list, tuple and dict) and types that correspond to types in the collections module (such as DefaultDict and Counter). You should consult the official Python documentation here to get a full list of all types. This tutorial shows you exa

List, Dict, Set, Frozenset

Since Python 3.9 you can use the builtins types (list, dict, set, frozenset) to type-hint

def unique_words(s: str) -> list[str]:
    """Return a list of the unique words in the given string."""
    words = s.split()
    unique_words = []
    for word in words:
        if word not in unique_words:
            unique_words.append(word)
    return unique_words

def count_words(s: str) -> dict[str, int]:
    """Count the number of occurrences of each word in the given string."""
    words = s.split()
    word_counts = {}
    for word in words:
        if word in word_counts:
            word_counts[word] += 1
        else:
            word_counts[word] = 1
    return word_counts


def intersection(set1: set[int], set2: set[int]) -> set[int]:
    """Return the intersection of the two given sets."""
    return set1 & set2

def intersection(set1: frozenset[int], set2: frozenset[int]) -> frozenset[int]:
    """Return the intersection of the two given frozen sets."""
    return set1 & set2

Deprecated types: List, Dict, Set, FrozenSet

If you are using a Python version prior to 3.9, you will have to use types from the typing module: typing.List, typing.Dict, typing.Set, typing.FrozenSet

from typing import List, Dict, Set, FrozenSet

def unique_words(s: str) -> List[str]:
    """Return a list of the unique words in the given string."""
    words = s.split()
    unique_words = []
    for word in words:
        if word not in unique_words:
            unique_words.append(word)
    return unique_words


def count_words(s: str) -> Dict[str, int]:
    """Count the number of occurrences of each word in the given string."""
    words = s.split()
    word_counts = {}
    for word in words:
        if word in word_counts:
            word_counts[word] += 1
        else:
            word_counts[word] = 1
    return word_counts


def union(set1: Set[int], set2: Set[int]) -> Set[int]:
    """Return the union of the two given sets."""
    return set1 | set2


def intersection(set1: FrozenSet[int], set2: FrozenSet[int]) -> FrozenSet[int]:
    """Return the intersection of the two given frozen sets."""
    return set1 & set2

Corresponding to types in collections

def count_words(s: str) -> DefaultDict[str, int]:
    """Count the number of occurrences of each word in the given string and return the results in a default dictionary."""
    words = s.split()
    word_counts = DefaultDict(int)
    for word in words:
        word_counts[word] += 1
    return word_counts


def sort_words(s: str) -> OrderedDict[int, str]:
    """Count the number of occurrences of each word in the given string and return the results in an ordered dictionary sorted by count."""
    words = s.split()
    word_counts = {}
    for word in words:
        if word in word_counts:
            word_counts[word] += 1
        else:
            word_counts[word] = 1
    return OrderedDict(sorted(word_counts.items(), key=lambda item: item[1]))


def merge_dicts(dict1: dict, dict2: dict) -> ChainMap:
    """Merge the two given dictionaries into a single chain map."""
    return ChainMap(dict1, dict2)


def count_characters(s: str) -> Counter[str]:
    """Count the number of occurrences of each character in the given string and return the results in a counter."""
    return Counter(s)


def process_data(data: Deque[int]) -> None:
    """Process the elements of the given deque."""
    while data:
        # do something with the data
        data.popleft()