In Python, can I lock a dict to only accept keys given to it at initialization?
- User
In Python, can I lock a dict to only accept keys given to it at initialization?
- Assistant
In Python, dictionaries are inherently mutable and do not have built-in mechanisms to restrict their keys after initialization. However, you can create a custom dictionary-like class that enforces this behavior. Here are a few approaches:
1. Using a Custom Dictionary Class
You can subclass
dictand override methods that modify keys (like__setitem__,update, etc.) to only allow keys that were present at initialization.class LockedDict(dict): def __init__(self, initial_keys, *args, **kwargs): super().__init__(*args, **kwargs) self._allowed_keys = set(initial_keys) def __setitem__(self, key, value): if key not in self._allowed_keys: raise KeyError(f"Key '{key}' is not allowed. Allowed keys: {self._allowed_keys}") super().__setitem__(key, value) def update(self, *args, **kwargs): for key in kwargs: if key not in self._allowed_keys: raise KeyError(f"Key '{key}' is not allowed. Allowed keys: {self._allowed_keys}") super().update(*args, **kwargs) def setdefault(self, key, default=None): if key not in self._allowed_keys: raise KeyError(f"Key '{key}' is not allowed. Allowed keys: {self._allowed_keys}") return super().setdefault(key, default) def pop(self, key, *args): if key not in self._allowed_keys: raise KeyError(f"Key '{key}' is not allowed. Allowed keys: {self._allowed_keys}") return super().pop(key, *args)Example Usage:
initial_keys = ['x', 'y', 'z'] locked_dict = LockedDict(initial_keys, x=1.0, y=2.0, z=3.0) # Allowed locked_dict['x'] = 10.0 # Not allowed (raises KeyError) locked_dict['w'] = 4.02. Using
types.MappingProxyType(Immutable Wrapper)If you want a completely immutable dictionary (no modifications allowed at all), you can use
types.MappingProxyType:from types import MappingProxyType initial_dict = {'x': 1.0, 'y': 2.0, 'z': 3.0} locked_dict = MappingProxyType(initial_dict) # Allowed print(locked_dict['x']) # Not allowed (raises TypeError) locked_dict['x'] = 10.0However, this does not allow any modifications, so it's stricter than what you asked for.
3. Using
@propertyin a Class (Alternative Approach)If you're working within a class, you can enforce key restrictions using properties:
class MyClass: def __init__(self, x, y, z): self._data = {'x': x, 'y': y, 'z': z} @property def data(self): return self._data @data.setter def data(self, value): if set(value.keys()) != {'x', 'y', 'z'}: raise ValueError("Only keys 'x', 'y', 'z' are allowed.") self._data = valueExample Usage:
obj = MyClass(1.0, 2.0, 3.0) # Allowed obj.data = {'x': 10.0, 'y': 20.0, 'z': 30.0} # Not allowed (raises ValueError) obj.data = {'x': 10.0, 'y': 20.0, 'w': 30.0}Summary:
- If you need a mutable dictionary with restricted keys, use
LockedDict. - If you need a completely immutable dictionary, use
MappingProxyType. - If you're working within a class, use properties to enforce restrictions.
Would you like any refinements or additional features?
- If you need a mutable dictionary with restricted keys, use
- User
Why does the following validation use a set representation of the dictionary keys? Shouldn't those already have no repetitions?
@position.setter def position(self, value: dict[str, float]): if not isinstance(value, dict) or set(value.keys()) != {"x", "y", "z"}: raise ValueError( "Position must be a dictionary with keys 'x', 'y', 'z'." ) self._position = value self._callback() - Assistant
You're absolutely right to question this! The use of
set(value.keys())in this validation is redundant because dictionary keys in Python are inherently unique—no duplicates are allowed. So,value.keys()is already a collection of unique keys, and converting it to a set doesn't change that.Why is
set(value.keys())used here?The primary reason is likely convenience for comparison. The code is checking if the keys of
valueare exactly{"x", "y", "z"}. Comparing sets is straightforward and intuitive:if set(value.keys()) != {"x", "y", "z"}: raise ValueError(...)This is equivalent to checking:
if sorted(value.keys()) != ["x", "y", "z"]: raise ValueError(...)But using sets is cleaner because:
- Order doesn't matter (sets are unordered, so
{"x", "y", "z"}is the same as{"z", "y", "x"}). - No need for sorting, which is slightly more efficient.
Could we skip the
set()conversion?Yes! Since dictionary keys are unique, we could directly compare
value.keys()with{"x", "y", "z"}:if value.keys() != {"x", "y", "z"}: raise ValueError(...)This works because
dict.keys()returns adict_keysobject, which supports set-like operations (including==comparison with a set).Which is better?
set(value.keys())is slightly more explicit and may be more readable for some developers.value.keys()is marginally more efficient (avoids creating a new set), but the difference is negligible in most cases.
Final Verdict:
The
set()conversion is unnecessary but harmless. If you prefer minimalism, you could rewrite it as:if not isinstance(value, dict) or value.keys() != {"x", "y", "z"}: raise ValueError("Position must be a dictionary with keys 'x', 'y', 'z'.")But the original version is fine too—it's a matter of style.
Would you like any further refinements to the validation logic?
- Order doesn't matter (sets are unordered, so
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.