[Python]Dict 및 Set 심화

Dict 및 Set 의 심화 사용방법에 대해 알아보자.

# Dict 및 Set 심화

# Immutable Dict
from types import MappingProxyType

# 수정가능한 set
d = {'key': 'value1'}

# 읽기전용
d_frozen = MappingProxyType(d)

print(d, id(d))
print(d_frozen, id(d_frozen))
'''
{'key': 'value1'} 2265773457920
{'key': 'value1'} 2265776994624
'''

# 수정가능
d['key2'] = 'value2'
print(d)
'''
{'key': 'value1', 'key2': 'value2'}
'''

# 수정불가 : 에러발생(TypeError: 'mappingproxy' object does not support item assignment)
# d_frozen['key2'] = 'value2'

print()

# Set 선언형태
s1 = {'orange', 'apple', 'orange', 'apple', 'grape'}
s2 = set(['orange', 'apple', 'orange', 'apple', 'grape'])
s3 = {3}
s4 = set()
s5 = frozenset({'orange', 'apple', 'orange', 'apple', 'grape'})

# 수정가능
s1.add('melon')

# 수정 불가 : 에러발생(AttributeError: 'frozenset' object has no attribute 'add')
# s5.add('melon')

print(s1, type(s1))
print(s2, type(s2))
print(s3, type(s3))
print(s4, type(s4))
print(s5, type(s5))
'''
{'apple', 'orange', 'grape', 'melon'}
{'apple', 'orange', 'grape', 'melon'} <class 'set'>
{'apple', 'orange', 'grape'} <class 'set'>
{3} <class 'set'>
set() <class 'set'>
frozenset({'apple', 'orange', 'grape'}) <class 'frozenset'>
'''

print()

# 선언최적화
# 파이썬은 바이트코드를 실행한다.
# dis는 파이썬의 내부적인 실행순서를 보여주는 함수
from dis import dis

# set을 선언하는 아래 2가지 방법 중에서 첫번째 방법(d={10})이 더 빠르다.
# d = {10}
# d = set([10])

print('-' * 10)
print(dis('{10}'))
print('-' * 10)
print(dis('set([10])'))
print()
'''
----------
  1           0 LOAD_CONST               0 (10)
              2 BUILD_SET                1
              4 RETURN_VALUE
None
----------
  1           0 LOAD_NAME                0 (set)
              2 LOAD_CONST               0 (10)
              4 BUILD_LIST               1
              6 CALL_FUNCTION            1
              8 RETURN_VALUE
None
'''

# 지능형 집합(Comprehending Set)
cd = {i for i in range(10)}
print(cd)
'''
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
'''

You may also like...

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다