https://docs.python.org/3.3/library/collections.html#defaultdict-objects
8.3. collections — Container datatypes — Python 3.3.7 documentation
8.3. collections — Container datatypes Source code: Lib/collections/__init__.py This module implements specialized container datatypes providing alternatives to Python’s general purpose built-in containers, dict, list, set, and tuple. namedtuple() fact
docs.python.org
Python으로 PS를 하면서 자주 쓰이는 defaultdict
오브젝트
기본적으로 dict 와 거의 동일하게 쓰이지만 이름에서 유추할 수 있듯 기본 값을 default_factory
라는 인자로 받을 수 있다.
defaultdict
예시 : key 값으로 묶기
>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for key, value in s:
... d[key].append(value)
...
>>> list(d.items())
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
공식 문서의 예제를 보면 s
라는 tuple로 이루어진 list의 값들을 이용하여 defaultdict
오브젝트인 d
에 넣어주고 있다.
list를 default_factory
값으로 받으면 key-value 쌍을 list의 dict 형으로 그룹으로 묶기에 간편하다!
코딩 테스트 등에서 key 값으로 그룹핑을 해야 하는 경우가 종종 생기는데 그럴 때 유용하게 쓸 수 있다.
defaultdict
예시 : 개수 세기
>>> s = 'mississippi'
>>> d = defaultdict(int)
>>> for k in s:
... d[k] += 1
...
>>> list(d.items())
[('i', 4), ('p', 2), ('s', 4), ('m', 1)]
default_factory
값을 int 형으로 받으면 카운팅으로도 활용 할 수 있다.
'PS > Python' 카테고리의 다른 글
[Python] 다중 할당 과 passed by assignment (1) | 2023.01.26 |
---|