python dict 순차자료형에서 생성

Haein Kim·2021년 9월 19일
1

TIL

목록 보기
12/14
In [58]: words = ['apple', 'bat', 'bar', 'atom', 'book']

In [59]: by_letter={}

In [61]: for word in words:
    ...:     ...:     letter = word[0]
    ...:     ...:     if letter not in by_letter:
    ...:     ...:         by_letter[letter] = [word]
    ...:     ...:     else:
    ...:     ...:         by_letter[letter].append(word)
    
In [62]: by_letter
Out[62]: {'a': ['apple', 'apple', 'atom'], 'b': ['bat', 'bat', 'bar', 'book']}
  • 내장 collections 모듈은 defaultdict 라는 클래스를 담고 있는데, 위 과정을 쉽게 하 ㄹ수 있다.
profile
콘텐츠를 사랑하는 데이터 분석가

0개의 댓글