Files
ruff/crates/ty_python_semantic/resources/mdtest/literal/collections/dictionary.md
Ibraheem Ahmed bea92c8229 [ty] More precise type inference for dictionary literals (#20523)
## Summary

Extends https://github.com/astral-sh/ruff/pull/20360 to dictionary
literals. This also improves our `TypeDict` support by passing through
nested type context.
2025-09-24 18:12:00 -04:00

1018 B

Dictionaries

Empty dictionary

reveal_type({})  # revealed: dict[Unknown, Unknown]

Basic dict

reveal_type({1: 1, 2: 1})  # revealed: dict[Unknown | int, Unknown | int]

Dict of tuples

reveal_type({1: (1, 2), 2: (3, 4)})  # revealed: dict[Unknown | int, Unknown | tuple[int, int]]

Unpacked dict

a = {"a": 1, "b": 2}
b = {"c": 3, "d": 4}

d = {**a, **b}
reveal_type(d)  # revealed: dict[Unknown | str, Unknown | int]

Dict of functions

def a(_: int) -> int:
    return 0

def b(_: int) -> int:
    return 1

x = {1: a, 2: b}
reveal_type(x)  # revealed: dict[Unknown | int, Unknown | ((_: int) -> int)]

Mixed dict

# revealed: dict[Unknown | str, Unknown | int | tuple[int, int] | tuple[int, int, int]]
reveal_type({"a": 1, "b": (1, 2), "c": (1, 2, 3)})

Dict comprehensions

# revealed: dict[@Todo(dict comprehension key type), @Todo(dict comprehension value type)]
reveal_type({x: y for x, y in enumerate(range(42))})