최대 크기를 가지는 딕셔너리 (LimitedSizeDict
)
이 예제에서는 딕셔너리에 추가할 수 있는 항목의 수를 제한합니다. 예를 들어, 최대 5개의 항목만 허용하도록 설정할 수 있습니다.
코드 설명
__init__
: 최대 크기를 설정합니다.__setitem__
: 딕셔너리의 크기가 최대 크기보다 크지 않은지 확인하고, 초과할 경우 예외를 발생시킵니다.update
: 추가될 항목의 수를 확인하여 제한을 적용합니다.
코드 샘플
class LimitedSizeDict(dict):
def __init__(self, *args, max_size=5, **kwargs):
self.max_size = max_size
super().__init__(*args, **kwargs)
if len(self) > self.max_size:
raise ValueError(f"Initial data exceeds the maximum size of {self.max_size}")
def __setitem__(self, key, value):
if key not in self and len(self) >= self.max_size:
raise KeyError(f"Cannot add new key '{key}'. Maximum size of {self.max_size} reached.")
super().__setitem__(key, value)
def update(self, *args, **kwargs):
additional_keys = 0
if args:
if isinstance(args[0], dict):
for key in args[0]:
if key not in self:
additional_keys += 1
elif isinstance(args[0], (list, tuple)):
for key, _ in args[0]:
if key not in self:
additional_keys += 1
else:
raise TypeError("Invalid argument type for update")
for key in kwargs:
if key not in self:
additional_keys += 1
if len(self) + additional_keys > self.max_size:
raise KeyError(f"Cannot add {additional_keys} new keys. Maximum size of {self.max_size} would be exceeded.")
super().update(*args, **kwargs)
# 사용 예제
try:
limited_dict = LimitedSizeDict(a=1, b=2, c=3, d=4, e=5, max_size=5)
print(limited_dict) # 출력: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
# 기존 키 수정
limited_dict['a'] = 10
print(limited_dict) # 출력: {'a': 10, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
# 새로운 키 추가 시도
limited_dict['f'] = 6 # KeyError 발생
except KeyError as e:
print(e) # 출력: Cannot add new key 'f'. Maximum size of 5 reached.
try:
# update 메서드로 새로운 키 추가 시도
limited_dict.update({'f': 6, 'g': 7}) # KeyError 발생
except KeyError as e:
print(e) # 출력: Cannot add 2 new keys. Maximum size of 5 would be exceeded.
출력 결과
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
{'a': 10, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
"Cannot add new key 'f'. Maximum size of 5 reached."
"Cannot add 2 new keys. Maximum size of 5 would be exceeded."
'실용적인 코드 샘플' 카테고리의 다른 글
[실용적인 코드 샘플] 제너릭을 이용한 `Triple` 자료구조 1 (2) | 2024.10.16 |
---|---|
[실용적인 코드 샘플] 특정 키와 값의 타입을 제한하는 딕셔너리 (TypedDict) (2) | 2024.10.16 |
[실용적인 코드 샘플] 읽기 전용 딕셔너리(ReadOnlyDict) (2) | 2024.10.16 |
[실용적인 코드 샘플] 제너릭을 이용한 `Pair` 클래스 1 (1) | 2024.10.15 |
[실용적인 코드 샘플] 고정 키 집합을 가지는 딕셔너리 (FixedKeysDict) (0) | 2024.10.15 |