📕 dictionary(딕셔너리)
Key와 Value를 한 쌍으로 가지는 자료형
dictionary = {"bannana": 1, "melon": 3}
해시 함수가 구현되어있는 형태이기도 하다.
defaultdict
defaultdict은 collections 라이브러리의 모듈이다.
dictionary는 존재하지 않는 키를 참조하려고 할 때 검사를 해주어야하는데, 이러한 번거로움을 해결 해주는 것이 defaultdict이다.
타입을 입력받으면 입력받은 타입의 기본값을 존재하지 않는 키의 기본값으로 사용한다.
from collections import defaultdict
default_dict = defaultdict(dict)
default_dict["apple"] = 1
default_dict["grape"]
list to dictionary
list안의 원소가 두 개씩 쌍으로 이루어져 있다면 dictionary로 바꾸어서 푸는 것이 효율적이기도하다.
list = [["rardss", "123"], ["yyoom", "1234"], ["meosseugi", "1234"]]
res = dict(list).get("rardss")
print(res)
# 123
dict(list)를 하면 dictionary 형식으로 바뀐다.(키 : 값 의 형식)
list안의 원소 형식이 list가 아니라도 상관없다.
key in dict
dictionary의 in 연산자는 시간복잡도가 O(1)이다.
즉, 배열에 in 연산자(O(n))보다 훨씬 효율적이다.