Python의 Defaultdict
사전 Python에서 지도와 같은 데이터 값을 저장하는 데 사용되는 순서가 지정되지 않은 데이터 값 모음입니다. 단일 값만 요소로 보유하는 다른 데이터 유형과 달리 사전은 키-값 쌍을 보유합니다. 사전에서 키는 고유하고 변경할 수 없어야 합니다. 이는 Python Tuple이 키가 될 수 있지만 Python List는 키가 될 수 없음을 의미합니다. 사전은 중괄호 {} 안에 '쉼표'로 구분된 일련의 요소를 배치하여 생성할 수 있습니다.
예:
파이썬3
# Python program to demonstrate> # dictionary> > > Dict> => {> 1> :> 'Geeks'> ,> 2> :> 'For'> ,> 3> :> 'Geeks'> }> print> (> 'Dictionary:'> )> print> (> Dict> )> print> (> Dict> [> 1> ])> > # Uncommenting this print(Dict[4])> # will raise a KeyError as the> # 4 is not present in the dictionary> |
산출:
Dictionary: {1: 'Geeks', 2: 'For', 3: 'Geeks'} Geeks Traceback (most recent call last): File '/home/1ca83108cc81344dc7137900693ced08.py', line 11, in print(Dict[4]) KeyError: 4
때로는 KeyError가 발생하면 문제가 될 수도 있습니다. 이 문제를 극복하기 위해 Python은 다음과 같은 컨테이너와 같은 또 다른 사전을 도입합니다. 불이행 컬렉션 모듈 내부에 있습니다.
메모: 자세한 내용은 다음을 참조하세요. 파이썬 사전 .
기본사전
불이행 다음과 같은 컨테이너입니다 사전 모듈에 존재 컬렉션 . Defaultdict는 사전과 유사한 객체를 반환하는 사전 클래스의 하위 클래스입니다. defaultdict가 KeyError를 발생시키지 않는다는 점을 제외하면 사전과 defaultdict의 기능은 거의 동일합니다. 존재하지 않는 키에 대한 기본값을 제공합니다.
통사론: defaultdict(default_factory)
매개변수:default_factory: 정의된 사전에 대한 기본값을 반환하는 함수입니다. 이 인수가 없으면 사전에서 KeyError가 발생합니다.
예:
파이썬3
# Python program to demonstrate> # defaultdict> > > from> collections> import> defaultdict> > > # Function to return a default> # values for keys that is not> # present> def> def_value():> > return> 'Not Present'> > # Defining the dict> d> => defaultdict(def_value)> d[> 'a'> ]> => 1> d[> 'b'> ]> => 2> > print> (d[> 'a'> ])> print> (d[> 'b'> ])> print> (d[> 'c'> ])> |
산출:
1 2 Not Present
defaultdict의 내부 작업
Defaultdict는 표준 사전 작업 외에 쓰기 가능한 인스턴스 변수 하나와 메서드 하나를 추가합니다. 인스턴스 변수는 default_factory 매개변수이고 제공된 메소드는 __missing__입니다.
- Default_factory: 정의된 사전에 대한 기본값을 반환하는 함수입니다. 이 인수가 없으면 사전에서 KeyError가 발생합니다.
예:
파이썬3
# Python program to demonstrate> # default_factory argument of> # defaultdict> > > from> collections> import> defaultdict> > > # Defining the dict and passing> # lambda as default_factory argument> d> => defaultdict(> lambda> :> 'Not Present'> )> d[> 'a'> ]> => 1> d[> 'b'> ]> => 2> > print> (d[> 'a'> ])> print> (d[> 'b'> ])> print> (d[> 'c'> ])> |
산출:
1 2 Not Present
- __missing__(): 이 함수는 사전의 기본값을 제공하는 데 사용됩니다. 이 함수는 default_factory를 인수로 취하고 이 인수가 None이면 KeyError가 발생하고 그렇지 않으면 주어진 키에 대한 기본값을 제공합니다. 이 메소드는 기본적으로 요청된 키를 찾을 수 없을 때 dict 클래스의 __getitem__() 메소드에 의해 호출됩니다. __getitem__()은 __missing__()이 반환한 값을 올리거나 반환합니다. 방법.
예:
파이썬3
# Python program to demonstrate> # defaultdict> > > from> collections> import> defaultdict> > > # Defining the dict> d> => defaultdict(> lambda> :> 'Not Present'> )> d[> 'a'> ]> => 1> d[> 'b'> ]> => 2> > # Provides the default value> # for the key> print> (d.__missing__(> 'a'> ))> print> (d.__missing__(> 'd'> ))> |
산출:
Not Present Not Present
List를 default_factory로 사용
목록 클래스가 default_factory 인수로 전달되면 목록 값을 사용하여 defaultdict가 생성됩니다.
예:
파이썬3
# Python program to demonstrate> # defaultdict> > > from> collections> import> defaultdict> > > # Defining a dict> d> => defaultdict(> list> )> > for> i> in> range> (> 5> ):> > d[i].append(i)> > print> (> 'Dictionary with values as list:'> )> print> (d)> |
산출:
Dictionary with values as list: defaultdict(, {0: [0], 1: [1], 2: [2], 3: [3], 4: [4]}) int를 default_factory로 사용
int 클래스가 default_factory 인수로 전달되면 기본값이 0인 defaultdict가 생성됩니다.
예:
파이썬3
# Python program to demonstrate> # defaultdict> > > from> collections> import> defaultdict> > > # Defining the dict> d> => defaultdict(> int> )> > L> => [> 1> ,> 2> ,> 3> ,> 4> ,> 2> ,> 4> ,> 1> ,> 2> ]> > # Iterate through the list> # for keeping the count> for> i> in> L:> > > # The default value is 0> > # so there is no need to> > # enter the key first> > d[i]> +> => 1> > print> (d)> |
산출:
defaultdict(, {1: 2, 2: 3, 3: 1, 4: 2})