dict 기본값 처리 (collections.defaultdict)

Han Hanju·2021년 10월 20일
0
post-thumbnail

1. 일반적인 사전 기본값 처리

def countLetters(word):
    counter = {}
    for letter in word:
        if letter not in counter:
            counter[letter] = 0
        counter[letter] += 1
    return counter

2. collection사용

from collections import defaultdict

def countLetters(word):
    counter = defaultdict(int)
    for letter in word:
        counter[letter] += 1
    return counter

Reference

https://www.daleseo.com/python-collections-defaultdict/

profile
Data Analytics Engineer

0개의 댓글