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_c2ee2fc6e40f0ee9.webp)
![[Python Cheatsheet] 28. itertools & functools - 자주 쓰는 조합](/post/python-cheatsheet/efficient-iteration-caching-itertools-functools-productivity-guide/wordcloud_hu_9de9b6bc855451b.webp)
![[Python Cheatsheet] 29. operator - 연산자 함수와 효율적 접근자](/post/python-cheatsheet/efficient-operator-module-guide-for-sorting-functional-patterns/wordcloud_hu_ccfe1db60a2f866a.webp)
![[Python Cheatsheet] 30. collections 심화 - deque/namedtuple/ChainMap](/post/python-cheatsheet/effective-collections-deque-namedtuple-chainmap-advanced-guide/wordcloud_hu_d825cfa100af3bf6.webp)
![[Python Cheatsheet] 31. heapq & bisect - 우선순위 큐/이진 검색 패턴](/post/python-cheatsheet/heapq-bisect-priority-queue-binary-search-guide/wordcloud_hu_79e1ae223a5bd420.webp)
![[Python Cheatsheet] 32. contextlib 심화 - suppress, redirect, ExitStack](/post/python-cheatsheet/contextlib-advanced-suppress-redirect-exitstack-nullcontext-examples/wordcloud_hu_63614113bfad58c2.webp)
![[Python Cheatsheet] 04. Collections - list/tuple/set 패턴](/post/python-cheatsheet/fast-list-tuple-set-guide-patterns-collection-copy-sort-unpack/wordcloud_hu_6ca3819a44ebde8f.webp)
![[Python Cheatsheet] 35. JSON & CSV - 읽기/쓰기/인코딩](/post/python-cheatsheet/read-write-json-csv-file-serialization-encoding-guide/wordcloud_hu_63bd30a4ad66950c.webp)
![[Python Cheatsheet] 53. shutil & tempfile - 파일/디렉토리 복사/이동/임시파일](/post/python-cheatsheet/file-directory-automation-shutil-tempfile-best-practices/wordcloud_hu_552ca129404266e1.webp)
![[Python Cheatsheet] 03. Strings - 슬라이싱/포맷팅/검색/치환](/post/python-cheatsheet/string-slicing-format-find-replace-text-guide-fast/wordcloud_hu_29a5b469feb985a1.webp)
![[Python Cheatsheet] 21. Enum & Flag - 열거형 실전 패턴](/post/python-cheatsheet/enum-flag-intenum-strenum-auto-bitwise-guide-best-patterns/wordcloud_hu_c5e80eb17669433.webp)