Yes, you can create a "locked" dictionary in Python that only accepts keys provided at initialization by subclassing dict or by creating a custom class that wraps a dictionary. This involves overriding methods like __setitem__ to enforce the restriction. Below are two approaches to achieve this:
Approach 1: Subclassing dict
You can subclass dict and override __setitem__ to prevent adding new keys after initialization. Here's an example:
class LockedDict(dict):
def __init__(self, initial_data=None):
if initial_data is None:
initial_data = {}
super().__init__(initial_data)
self._locked_keys = set(self.keys())
def __setitem__(self, key, value):
if key not in self._locked_keys:
raise KeyError(f"Cannot add new key '{key}'. Only keys {self._locked_keys} are allowed.")
super().__setitem__(key, value)
def update(self, *args, **kwargs):
# Handle updates but restrict to existing keys
if args:
other = args[0]
if isinstance(other, dict):
for key in other:
if key not in self._locked_keys:
raise KeyError(f"Cannot add new key '{key}'. Only keys {self._locked_keys} are allowed.")
for key in kwargs:
if key not in self._locked_keys:
raise KeyError(f"Cannot add new key '{key}'. Only keys {self._locked_keys} are allowed.")
super().update(*args, **kwargs)
def __delitem__(self, key):
raise KeyError("Cannot delete keys from a LockedDict.")
def pop(self, key, *args):
raise KeyError("Cannot pop keys from a LockedDict.")
def popitem(self):
raise KeyError("Cannot pop items from a LockedDict.")
def clear(self):
raise KeyError("Cannot clear a LockedDict.")
Example Usage:
# Create a locked dictionary
locked_dict = LockedDict({'x': 1, 'y': 2, 'z': 3})
# Modify existing keys (allowed)
locked_dict['x'] = 10
print(locked_dict) # {'x': 10, 'y': 2, 'z': 3}
# Try to add a new key (raises error)
try:
locked_dict['w'] = 4
except KeyError as e:
print(e) # "Cannot add new key 'w'. Only keys {'x', 'y', 'z'} are allowed."
# Try to update with new keys (raises error)
try:
locked_dict.update({'w': 4})
except KeyError as e:
print(e) # "Cannot add new key 'w'. Only keys {'x', 'y', 'z'} are allowed."
# Try to update with existing keys (allowed)
locked_dict.update({'x': 20, 'y': 30})
print(locked_dict) # {'x': 20, 'y': 30, 'z': 3}
# Try to delete a key (raises error)
try:
del locked_dict['x']
except KeyError as e:
print(e) # "Cannot delete keys from a LockedDict."
Approach 2: Using a Custom Class (Wrapper)
If you prefer not to subclass dict, you can create a custom class that wraps a dictionary and provides controlled access to it. This approach might be more flexible if you need additional functionality or if you want to avoid inheriting from dict.
class LockedDictWrapper:
def __init__(self, initial_data=None):
if initial_data is None:
initial_data = {}
self._data = dict(initial_data)
self._locked_keys = frozenset(self._data.keys())
def __getitem__(self, key):
if key not in self._locked_keys:
raise KeyError(f"Key '{key}' does not exist. Only keys {self._locked_keys} are allowed.")
return self._data[key]
def __setitem__(self, key, value):
if key not in self._locked_keys:
raise KeyError(f"Cannot add new key '{key}'. Only keys {self._locked_keys} are allowed.")
self._data[key] = value
def __repr__(self):
return repr(self._data)
def __str__(self):
return str(self._data)
def get(self, key, default=None):
if key not in self._locked_keys:
return default
return self._data.get(key, default)
def keys(self):
return self._locked_keys
def values(self):
return [self._data[key] for key in self._locked_keys]
def items(self):
return [(key, self._data[key]) for key in self._locked_keys]
Example Usage:
# Create a locked dictionary wrapper
locked_dict = LockedDictWrapper({'x': 1, 'y': 2, 'z': 3})
# Modify existing keys (allowed)
locked_dict['x'] = 10
print(locked_dict) # {'x': 10, 'y': 2, 'z': 3}
# Try to add a new key (raises error)
try:
locked_dict['w'] = 4
except KeyError as e:
print(e) # "Cannot add new key 'w'. Only keys frozenset({'x', 'y', 'z'}) are allowed."
# Access keys
print(locked_dict['x']) # 10
# Try to access a non-existent key (raises error)
try:
print(locked_dict['w'])
except KeyError as e:
print(e) # "Key 'w' does not exist. Only keys frozenset({'x', 'y', 'z'}) are allowed."
# Use get method
print(locked_dict.get('w', 0)) # 0 (default value)
Key Differences Between Approaches:
-
Subclassing dict (Approach 1):
- Behaves like a dictionary, so it supports all dictionary methods (though some are restricted).
- More familiar to users expecting dictionary-like behavior.
- Slightly less flexible if you need to add non-dictionary behavior.
-
Custom Wrapper (Approach 2):
- Does not inherit from
dict, so you have full control over the interface.
- Requires implementing dictionary-like methods manually (e.g.,
keys(), values(), items()).
- More flexible for adding custom behavior or if you want to avoid dict-like behavior entirely.
Notes:
- Both approaches use a set (or
frozenset in the wrapper) to store the allowed keys, ensuring that the set of keys is immutable after initialization.
- If you need thread safety or additional features, you might need to add more logic (e.g., using locks for thread safety).
- If you want to allow changing the values of existing keys but prevent adding or removing keys, both implementations above achieve that goal.
Choose the approach that best fits your use case. If you need a drop-in replacement for a dictionary, Approach 1 is better. If you need a more controlled or custom interface, Approach 2 might be preferable.