카페에서 IT 산책 (일반)/Python
Python의 collection. defaultdict 설명 및 예제
카페힐링
2022. 12. 31. 21:55
반응형
Python의 collection의 자료형에는 defaultdict, orderdict, Count, NamedTuple 등이 있지요. ^^
내장 자료형의 Dictionary는 반듯이 key, value로 구성해서 생성해야 합니다.
하지만 key를 넣은 후 value가 없거나 적합하지 않을 경우 임의의 value로도 Dictionary 구성이 가능 합니다.
그것을 가능하게 하는 것이 defultdict 입니다.
defaultdict의 예제에 대해서 알아 보겠습니다.
예제1) defaultdict의 기본 예시
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("Dictionary:")
print(Dict)
print(Dict[1])
Output:
Dictionary:
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Geeks
예제2) defaultdict에서 key가 없을 경우 처리 예시
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"])
Output:
1
2
Not Present
예제3) defaultdict에서 default 값을 list로 줄 경우
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)
Output:
Dictionary with values as list:
defaultdict(<class 'list'>, {0: [0], 1: [1], 2: [2], 3: [3], 4: [4]})
예제4) defaultdict에서 default 값이 int인 경우1
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)
Output:
defaultdict(<class 'int'>, {1: 2, 2: 3, 3: 1, 4: 2})
예제5) defaultdict에서 default 값이 int인 경우2
from collections import defaultdict
animals = ['dog', 'cat', 'rabbit', 'tiger', 'cat', 'cat', 'rabbit']
dic = defaultdict(int)
for animal in animals:
dic[animal] += 1
print(dic)
Output:
defaultdict(<class 'int'>, {'dog': 1, 'cat': 3, 'rabbit': 2, 'tiger': 1})
반응형