티스토리 뷰

개발/파이썬

collections.defaultdict() 활용법

맨날치킨 2022. 12. 12. 19:05
반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

How does collections.defaultdict work?

collections.defaultdict는 어떻게 작동하나요?

 문제 내용 

I've read the examples in python docs, but still can't figure out what this method means. Can somebody help? Here are two examples from the python docs

파이썬 문서의 예제를 읽었지만, 이 메소드가 무슨 의미인지 아직 모르겠습니다. 누군가 도와줄 수 있나요? 파이썬 문서에서 가져온 두 가지 예시입니다.
>>> from collections import defaultdict

>>> s = 'mississippi'
>>> d = defaultdict(int)
>>> for k in s:
...     d[k] += 1
...
>>> d.items()
[('i', 4), ('p', 2), ('s', 4), ('m', 1)]

 

and

그리고
>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
...     d[k].append(v)
...
>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

 

the parameters int and list are for what?

int와 list 매개변수는 무엇을 위한 것인가요?

 

 

 

 높은 점수를 받은 Solution 

Usually, a Python dictionary throws a KeyError if you try to get an item with a key that is not currently in the dictionary. The defaultdict in contrast will simply create any items that you try to access (provided of course they do not exist yet). To create such a "default" item, it calls the function object that you pass to the constructor (more precisely, it's an arbitrary "callable" object, which includes function and type objects). For the first example, default items are created using int(), which will return the integer object 0. For the second example, default items are created using list(), which returns a new empty list object.

보통 파이썬 딕셔너리는 현재 딕셔너리에 없는 키로 항목을 가져오려고 하면 KeyError를 발생시킵니다. defaultdict는 대조적으로, 당신이 접근하려는 모든 항목을 간단히 만듭니다 (물론 아직 존재하지 않는 경우). 이러한 "기본" 항목을 만들기 위해 생성자에 전달한 함수 객체를 호출합니다 (보다 정확히는 임의의 "callable" 객체, 즉 함수 및 타입 객체를 포함합니다). 첫 번째 예제에서 기본 항목은 int()를 사용하여 생성되며, 이는 정수 객체 0을 반환합니다. 두 번째 예제에서 기본 항목은 list()를 사용하여 생성되며, 이는 새로운 빈 리스트 객체를 반환합니다.

 

 

 

 가장 최근 달린 Solution 

The behavior of defaultdict can be easily mimicked using dict.setdefault instead of d[key] in every call.

defaultdict의 동작은 dict.setdefault을 사용하여 모든 호출에서 d[key] 대신에 복제할 수 있습니다.

 

In other words, the code:

즉, 코드:
from collections import defaultdict

d = defaultdict(list)

print(d['key'])                        # empty list []
d['key'].append(1)                     # adding constant 1 to the list
print(d['key'])                        # list containing the constant [1]

 

is equivalent to:

는 다음과 같습니다.
d = dict()

print(d.setdefault('key', list()))     # empty list []
d.setdefault('key', list()).append(1)  # adding constant 1 to the list
print(d.setdefault('key', list()))     # list containing the constant [1]

 

The only difference is that, using defaultdict, the list constructor is called only once, and using dict.setdefault the list constructor is called more often (but the code may be rewriten to avoid this, if really needed).

유일한 차이점은 defaultdict를 사용하면 list 생성자가 한 번만 호출되지만, dict.setdefault를 사용하면 list 생성자가 더 자주 호출됩니다 (하지만 필요하다면 코드를 재작성하여 이를 회피할 수 있습니다).

 

Some may argue there is a performance consideration, but this topic is a minefield. This post shows there isn't a big performance gain in using defaultdict, for example.

성능 고려사항이 있다는 주장도 있지만, 이 주제는 아주 민감한 문제입니다. 예를 들어 이 게시물은 defaultdict를 사용하여 큰 성능 향상이 없다는 것을 보여줍니다.

 

IMO, defaultdict is a collection that adds more confusion than benefits to the code. Useless for me, but others may think different.

개인적으로는 defaultdict는 코드에 혼란을 더 불러오는 컬렉션인 것 같습니다. 나에게는 쓸모 없지만, 다른 사람들은 다르게 생각할 수 있습니다.

 

 

 

출처 : https://stackoverflow.com/questions/5900578/how-does-collections-defaultdict-work

반응형
댓글
공지사항
최근에 올라온 글