적은 리소스로 많은 데이터를 효율적으로 관리
Dict → Key 중복 허용 X, Set → 중복 허용 X
Dict 및 Set 심화
from types import MappingProxyType
# 읽기 전용의 dict
d = {'key1': 'value1'} # 절대 수정 하면 안되는 값일경우!!
# Read Only
d_frozen = MappingProxyType(d)
print(d_frozen, id(d)) # hash 값 못 읽음
# 수정 가능
d['key2'] = 'value2'
print(d)
# 수정 불가 (예외를 사용한다.)
# d_frozen['key2'] = 'value2'
# print(d_frozen)
기본적으로 Dict형은 가변형인데, 이를 수정을 못하게 하는 방법이 있는데 그게 바로 라이브러리에서 지원하는 MappingProxyType이다.
특히나 이렇게 못읽게 만든건 fronze 이라는 변수를 넣어 사용하는 팁을 알려주었다.
s1 = {'Apple', 'Orange', 'Apple', 'Orange', 'Kiwi'}
s2 = set(['Apple', 'Orange', 'Apple', 'Orange', 'Kiwi'])
s3 = {3}
s4 = set() # Not {}
s5 = frozenset({'Apple', 'Orange', 'Apple', 'Orange', 'Kiwi'})
s1.add('Melon')
print(s1)
#추가 불가
# s5.add('Melon')
print(s1, type(s1))
print(s2, type(s2))
print(s3, type(s3))
print(s4, type(s4))
print(s5, type(s5))
#선언 최적화
# 바이트 코드 -> 파이썬 인터프리터 실행 (내부적으로 파이썬 작동 원리)
from dis import dis
print('------')
print(dis('{10}'))
print('------')
print(dis('set([10])'))
마지막 부분의 추가된 부분인데 바이트 코드가 파이썬 인터프리터 실행을 하는데, 가장 중요한건 그냥 바로 만드는게 훨씬 빠르다..
거치는 과정이 더 생긴다.
# 지능형 집합 (Comprehending Set)
from unicodedata import name
print({name(chr(i), '') for i in range(0, 256)})