본문 바로가기
C.W.K.
Stream
Lesson 03 of 05 · published

TypedDict — 딕셔너리의 키 모양 설명하기

~18 min · typeddict, structured-dict, notrequired

Level 0호기심
0 XP0/93 lessons0/23 achievements
0/100 XP to next level100 XP to go0% complete

TypedDict는 dict[str, Any]보다 어떤 키가 어떤 타입인지 구체적으로 적어. 클래스 문법이 보통 읽기 좋고, Python 식별자가 아닌 키가 필요하면 함수형 선언을 써. 기본 키는 필수이며 NotRequired, Required, total=False로 선택 여부를 정해.

실행 중에는 여전히 평범한 dict라 입력을 검증하지 않아. JSON 모양의 내부 정적 설명은 TypedDict, 속성 객체는 dataclass, 외부 경계 검증은 Pydantic으로 나눠.

Code

클래스 문법의 TypedDict·python
from typing import TypedDict

class User(TypedDict):
    name: str
    age: int
    email: str

def greet(u: User) -> str:
    return f"hi {u['name']} ({u['age']})"

u: User = {"name": "alice", "age": 30, "email": "a@x.com"}
print(greet(u))

# 런타임에 u 는 일반 dict
print(type(u))                         # <class 'dict'>
print(isinstance(u, dict))             # True
NotRequired로 선택 키 표시하기·python
from typing import TypedDict, NotRequired

class User(TypedDict):
    name: str
    age: int
    nickname: NotRequired[str]            # 옵션
    bio: NotRequired[str]                 # 옵션

minimal: User = {"name": "alice", "age": 30}                       # OK
full: User = {"name": "bob", "age": 25, "nickname": "b", "bio": "hi"}

# 3.11 이전 — total=False 가 모든 거 옵션
class Settings(TypedDict, total=False):
    theme: str
    font: str
    debug: bool

s: Settings = {}                       # OK — 모든 필드 옵션
s2: Settings = {"theme": "dark"}      # OK
식별자가 아닌 키의 함수형 선언·python
from typing import TypedDict

# 가끔 API 응답이 유효 Python 이름 아닌 키 가짐
# 함수형 스타일이 처리
GoogleApiResponse = TypedDict("GoogleApiResponse", {
    "status": str,
    "error-code": int,         # 키에 하이픈 — 무효 식별자
    "User-Agent": str,         # 대문자와 하이픈
})

resp: GoogleApiResponse = {
    "status": "ok",
    "error-code": 0,
    "User-Agent": "...",
}
TypedDict와 dataclass 고르기·python
from typing import TypedDict
from dataclasses import dataclass

# TypedDict — 체크된 구조 가진 dict 원할 때
class UserDict(TypedDict):
    name: str
    age: int

def use_dict(u: UserDict):
    print(u["name"])              # 대괄호 접근

# Dataclass — 속성 가진 클래스 원할 때
@dataclass
class UserClass:
    name: str
    age: int

def use_class(u: UserClass):
    print(u.name)                 # 속성 접근

# JSON in/out — TypedDict 가 wire 포맷에 더 가까움
# 도메인 로직 — dataclass 가 더 잘 읽힘

External links

Exercise

ticker, price, shares가 필수이고 note와 tags는 선택인 Stock TypedDict를 만들어. total_value(s: Stock) -> float를 작성하고 선택 키가 있는 값과 없는 값을 모두 시험해.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.