collections 모듈은 기본 자료구조를 확장한 특수 컨테이너를 제공합니다. 이 치트시트는 deque, namedtuple, ChainMap, OrderedDict의 실전 패턴을 정리합니다.
언제 이 치트시트를 보나?
- 양쪽 끝에서 효율적 삽입/삭제가 필요할 때 (deque)
- 읽기 쉬운 튜플(필드명 접근)이 필요할 때 (namedtuple)
- 여러 딕셔너리를 하나처럼 접근하고 싶을 때 (ChainMap)
핵심 패턴
deque: O(1) 양방향 삽입/삭제 +maxlen으로 고정 크기 버퍼namedtuple: 인덱스와 이름 둘 다로 접근 가능한 튜플ChainMap: 여러 딕셔너리를 순차 검색 (설정 우선순위 구현)OrderedDict: 삽입 순서 유지 (Py3.7+ dict도 유지하지만 추가 기능 있음)
deque - 양방향 큐
| |
| |
| |
namedtuple - 명명된 튜플
| |
| |
| |
| |
ChainMap - 딕셔너리 체인
| |
| |
| |
OrderedDict - 순서 유지 딕셔너리
| |
| |
Counter / defaultdict 복습
| |
자주 하는 실수/주의점
- deque 인덱싱 O(n): 중간 접근이 많으면 리스트 사용
- namedtuple은 불변: 변경 가능하면 dataclass 사용
- ChainMap 쓰기: 첫 번째 딕셔너리에만 적용됨
- Counter 음수:
subtraction은 음수를 만들지 않음 (subtract()는 만듦)
| |
![Featured image of post [Python Cheatsheet] 30. collections 심화 - deque/namedtuple/ChainMap](/post/python-cheatsheet/effective-collections-deque-namedtuple-chainmap-advanced-guide/wordcloud_hu_1b0c08b1ca95bd15.png)
![[Python Cheatsheet] 27. inspect - 런타임 객체 검사](/post/python-cheatsheet/inspect-module-runtime-analysis-introspection-reflection-guide/wordcloud_hu_70b5f20ea3261622.png)
![[Python Cheatsheet] 29. operator - 연산자 함수와 효율적 접근자](/post/python-cheatsheet/efficient-operator-module-guide-for-sorting-functional-patterns/wordcloud_hu_69b3cc6dc63a3941.png)
![[Python Cheatsheet] 30. collections 심화 - deque/namedtuple/ChainMap](/post/python-cheatsheet/effective-collections-deque-namedtuple-chainmap-advanced-guide/wordcloud_hu_cd891a80d48aba0f.png)
![[Python Cheatsheet] 31. heapq & bisect - 우선순위 큐/이진 검색 패턴](/post/python-cheatsheet/heapq-bisect-priority-queue-binary-search-guide/wordcloud_hu_2b6efde7c9bc727c.png)
![[Python Cheatsheet] 32. contextlib 심화 - suppress, redirect, ExitStack](/post/python-cheatsheet/contextlib-advanced-suppress-redirect-exitstack-nullcontext-examples/wordcloud_hu_ac7b663d88a59d6d.png)
![[Python Cheatsheet] 05. dict 패턴 - 조회/기본값/카운팅/병합](/post/python-cheatsheet/advanced-dictionary-patterns-safe-lookup-merging-counting/wordcloud_hu_a8ea7ce166a54814.png)
![[Python Cheatsheet] 04. Collections - list/tuple/set 패턴](/post/python-cheatsheet/fast-list-tuple-set-guide-patterns-collection-copy-sort-unpack/wordcloud_hu_bd6bf3a251c6426.png)
![[Python Cheatsheet] 63. asyncio - 비동기 최소 패턴](/post/python-cheatsheet/async-io-patterns-concurrency-coroutine-async-await-guide/wordcloud_hu_e60faafd6849ed23.png)
![[Python Cheatsheet] 64. Concurrency - threading/multiprocessing 선택](/post/python-cheatsheet/concurrency-guide-threading-vs-multiprocessing-explained-fast/wordcloud_hu_fa87651745dbb8a2.png)