dict를 구성하는 방법

Nam Eun-Ji·2020년 11월 27일
0

기본적으로 dictionary는 key마다 기본값들을 정해주어야 한다. 그래서 dictionary를 사용하기 위해서는 초기화 과정이 필요하다.

a = {}
b = ['a','b','c']
for x in b:
	if x not in a:
    	a[x] = 0
print(a)    # {'a': 0, 'b': 0, 'c': 0}


setdefault

key와 value를 인자로 받는다.

만약 해당 dict에 key가 이미 존재한다면, key와 value를 반환하고, 없다면 두번째 인자를 반환한다.

dict.setdefault(key, value)

예 1)

a = ['a', 'b', 'c']
check1 = {}

for x in a:
    check1.setdefault(x, 0)

>>> 0
>>> 0
>>> 0

print(check1)
>>> {'a': 0, 'b': 0, 'c': 0}

예 2)

a = ['a', 'b', 'c']
check2 = {'b': 2}

for x in a:
    check2.setdefault(x, 0)
    check2[x] += 1

>>> 0
>>> 2
>>> 0

print(check2)
>>> {'a': 1, 'b': 3, 'c': 1}


defaultdict

defaultdict 은 dict의 기본값을 정의하고 값이 없을 경우 에러를 출력하지 않고 기본값을 출력한다.
setdefault 보다 빠른 것이 장점이다.
collections.defaultdict(int) 에서 int 자리에는 list 혹은 다른 object 형태들로 지정가능하다.

예 1)

import collections

a = ['a','b','c']
d = collections.defaultdict(int)
print(d)    # defaultdict(<class 'int'>, {})

for x in a:
    d[x] += 1

print(d)
# {'a': 1, 'b': 1, 'c': 1}

예 2)

import collections

a = ['a','b','c']
d = collections.defaultdict(str)
print(d)    # defaultdict(<class 'str'>, {})

for x in a:
	d[x] += 1

# Traceback (most recent call last):
#   File "<stdin>", line 2, in <module>
# TypeError: can only concatenate str (not "int") to str

초기값을 str로 정해주었기 때문에 숫자를 더하니 에러가 난다.

profile
한 줄 소개가 자연스러워지는 그날까지

0개의 댓글