Python

[TIL] 220821 딕셔너리 get 메서드 사용하기 (get method for dictionaries), 딕셔너리 활용 빈도수 체크하기, 히스토그램 처럼 활용

kyra 2022. 8. 21. 10:58

The pattern of checking to see if a key is already in a dictionary and assuming a default value if the key is not there is so common that there is a method called get() that does this for us

 

if name in counts:
	x = counts[name]
else:
	x = 0

위의 식은 count라는 key를 모아놓은 리스트 안에 name이 있을 경우, x를 value값으로 출력하고, 없을 경우 0을 출력하는 코드이다. key가 이미 있는지 확인하는 이 패턴은 너무 많이 사용하기 때문에 get이라는 메서드로 더 간편하게 확인해볼 수 있다.

 

x  = counts.get(name, 0)

#0은 default 값이다.

 

이를 응용해서, key값이 있으면 value를 +1 하고, key가 없으면 딕셔너리에 새로운 key를 만들고 value를 0이라 하는 코드를 작성해 보았을 때,

counts = dict()
names = ['csev', 'cwen', 'csev', 'zqian', 'cwen']
for name in names:
	counts[name] = counts.get(name, 0) + 1
print(counts)

#{'csev' : 2, 'zqian' : 1, 'cwen' : 2} 출력

이렇게 주어진 리스트 안에 같은 이름이 몇개 있는지 빈도수를 확인하는 딕셔너리를 만들 수 있다.