defaultdict vs dict: 파이썬에서의 효율적인 카운팅 방법 비교

defaultdict와 dict를 사용하여 리스트에 있는 단어를 카운팅하는 방법을 비교합니다.



2024. 7. 9  최초작성



실행결과는 동일합니다. 

 

defaultdict 결과: {'apple': 3, 'banana': 2, 'cherry': 1, 'date': 1}

일반 dict 결과: {'apple': 3, 'banana': 2, 'cherry': 1, 'date': 1}




전체 코드입니다.

 

from collections import defaultdict


# 1. defaultdict를 사용한 카운팅
def count_with_defaultdict(items):

    # 해당 키가 없으면 자동으로 0으로 초기화되며 이후 1을 더하게 됩니다.
    counter = defaultdict(int)
   
    for item in items:
        counter[item] += 1
   
    return dict(counter)  # 일반 dict로 변환하여 반환


# 2. 일반 dict를 사용한 카운팅
def count_with_dict(items):

    # 해당 키가 없는 경우 수동으로 초기값 처리를 해줘야 합니다. 여기에선 한번 발견한 것도 처리하기 위해 1로 초기화합니다.
    counter = {}
    for item in items:
        if item in counter:
            counter[item] += 1
        else:
            counter[item] = 1
    return counter



# 카운팅할 단어를 리스트에 저장해둡니다. 리스트에 있는 중복 단어의 개수를 세보려고 합니다. 
words = ["apple", "banana", "apple", "cherry", "banana", "date", "apple"]

# 카운팅 결과를 비교합니다. 결과는 동일합니다.
print("defaultdict 결과:", count_with_defaultdict(words))
print("일반 dict 결과:", count_with_dict(words))




시간날때마다 틈틈이 이것저것 해보며 블로그에 글을 남깁니다.

블로그의 문서는 종종 최신 버전으로 업데이트됩니다.
여유 시간이 날때 진행하는 거라 언제 진행될지는 알 수 없습니다.



영화,책, 생각등을 올리는 블로그도 운영하고 있습니다.
https://freewriting2024.tistory.com


제가 쓴 책도 한번 검토해보세요 ^^