Fluent Python - Chap 3. 딕셔너리와 집합 (2)
이 포스트는 <<Fluent Python (전문가를 위한 파이썬) >> (written by Luciano Ramalho, 강권학 옮김) 스터디를 진행하면서 공부한 내용을 정리하는 목적으로 작성되었습니다. 따라서 이 포스트 내 설명 및 코드의 출처는 <<Fluent Python (전문가를 위한 파이썬) >> 임을 미리 밝힙니다. Chapter 3. 딕셔너리와 집합 3.4 융통성 있게 키를 조회하는 매핑 3.4.1 defaultdict: 존재하지 않는 키에 대한 또 다른 처리 저번 포스트에서 봤던 setdefault() 예제 코드를 다시 보자. import sys import re WORD_RE = re.compile(r'\w+') index={} with open(sys.argv[1]) as fp: for line_no, line in enumerate(fp, 1): for match in WORD_RE.finditer(line): word = match.group() column_no = match.start()+1 location = (line_no, column_no) index.setdefault(word, []).append(location) for word in sorted(index, key=str.upper): print(word, index[word]) 이때, index를 기본 dict 가 아닌 collections.defaultdict 객체로 생성하여 위 코드를 다시 쓸 수 있다. ...