코딩/파이썬

[python] 딕셔너리에서 기본값 설정하기

손느린 프로그래머 2023. 8. 1. 13:39
반응형

파이썬에서 가장 많이 사용하는 dictionary 는 간단히 key값만 있으면 원하는 정보를 찾을 수 있는 편리한 데이터 구조입니다. 하지만 가끔 key가 존재하지 않을 경우, 에러가 발생해서 불편함 있는데요. 이번 글에서는 딕셔너리에서 어떻게 디폴트 값을 설정하는지에 대해 알아보겠습니다. 

 

 

 


1. dict.get(key, default) 메서드 사용하기

  • dict의 get(key, default) 메소드를 이용하면, 디폴트값 설정이 가능하다. 

딕셔너리에서 키를 사용하여 값을 가져오는 가장 일반적인 방법은 대괄호([])를 사용하는 것입니다. 하지만, 이 방식의 단점은 딕셔너리에 해당 키가 없을 경우 KeyError가 발생한다는 점입니다. 이런 상황을 방지하기 위해 dict.get(key, default) 메서드를 사용할 수 있습니다.

dictionary = {"apple": 1, "banana": 2}
print(dictionary.get("apple", 0))  # 1
print(dictionary.get("cherry", 0)) # 0  : cherry 가 없어서 디폴트인 0을 출력함

위의 코드에서, "apple"은 딕셔너리에 존재하므로 해당 값인 1이 출력되고, "cherry"는 딕셔너리에 존재하지 않으므로 기본값인 0이 출력됩니다.


2. collections.defaultdict 사용하기

  • collections.defaultdict 초기값 생성 함수를 정의할 수 있다.

두 번째로 살펴볼 메서드는 collections.defaultdict입니다. 이 메서드를 사용하면, 딕셔너리에 없는 키를 조회할 때도 기본값을 반환할 수 있습니다. 기본값을 설정하기 위해서는 defaultdict를 생성할 때 초기화 함수를 전달해야 합니다.

 

from collections import defaultdict

# default는 반드시 호출가능해야 합니다. 
# 아래는 int() 의 결과인 0이 디폴트가 됩니다.
dictionary = defaultdict(int)
dictionary["apple"] = 1
dictionary["banana"] = 2

print(dictionary["apple"])   # 1
print(dictionary["cherry"])  # 0


# lambda : 'x' --> 문자열 x가 디폴트 값이 됩니다. 
dictionary = defaultdict( lambda : 'x' )
dictionary["apple"] = 'a'
dictionary["banana"] = 'b'

print(dictionary["apple"])   # 'a'
print(dictionary["cherry"])  # 'x'

위의 코드에서는 defaultdict(int)로 초기화 함수로 int를 전달했습니다. 따라서 딕셔너리에 없는 키를 조회하면 int()의 결과인 0이 반환됩니다.

 

 

아래는 defaultdict의 공식 문서입니다.

https://docs.python.org/ko/3/library/collections.html#collections.defaultdict

 

collections — Container datatypes

Source code: Lib/collections/__init__.py This module implements specialized container datatypes providing alternatives to Python’s general purpose built-in containers, dict, list, set, and tuple.,,...

docs.python.org


 

 

 

 

3. dict.setdefault(key, default) 메서드 사용하기

  • dict.setdefault(key, default) 로 key가 없으면 디폴트값으로 생성하기

마지막으로 살펴볼 메서드는 dict.setdefault(key, default)입니다. 이 메서드는 딕셔너리에 키가 없을 경우 새로운 키와 기본값을 추가합니다. 그리고 키에 대응하는 값을 반환합니다.

 

dictionary = {"apple": 1, "banana": 2}

# apple은 키가 있어서 해당값을 리턴함
print(dictionary.setdefault("apple", 0))   # 1

# cherry key를 생성하고 디폴트 값이 0을 설정함
print(dictionary.setdefault("cherry", 0))  # 0
print(dictionary)  # {'apple': 1, 'banana': 2, 'cherry': 0}

 

위의 코드에서 "apple"은 딕셔너리에 존재하므로 해당 값인 1이 출력되고, "cherry"는 딕셔너리에 존재하지 않으므로 기본값인 0이 출력되고, 동시에 {"cherry": 0}이 딕셔너리에 추가됩니다.

 

 

https://smart-worker.tistory.com/50

 

[Python]람다(lambda) 함수 이해하기

이 글에서는 Python 프로그래밍 언어에서 사용되는 람다(lambda) 함수에 대해 배울 것입니다. 초보자 분들도 쉽게 이해할 수 있도록 기본적인 개념부터 실제 사용 사례까지 자세히 설명하겠습니다.

smart-worker.tistory.com

 

 

https://smart-worker.tistory.com/49

 

[Python] 리스트와 튜플(tuple)의 차이점 이해하기

Python을 많이 사용하는 이유 중에 하나가, 기본 내장된 다양하고 잘 설계된 데이터 구조입니다. 많이 사용하는 데이터 구조로 리스트와 튜플이 있는데요. 초보자 분들이 리스트와 튜플을 많이 헷

smart-worker.tistory.com

 

 

 

반응형