Custom dict to prevent keys from being overridden
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Sat Aug 27 22:38:20 EDT 2011
Julien wrote:
> What I'd like to achieve is:
>
>>>> d = {
> ... 'a': 1,
> ... 'b': 2,
> ... 'a': 3
> ... }
> Error: The key 'a' already exists.
>
> Is that possible, and if so, how?
Not if the requirements including using built-in dicts { }.
But if you are happy enough to use a custom class, like this:
d = StrictDict(('a', 1), ('b', 2'), ('a', 3))
then yes. Just subclass dict and have it validate items as they are added.
Something like:
# Untested
class StrictDict(dict):
def __init__(self, items):
for key, value in items:
self[key] = value
def __setitem__(self, key, value):
if key in self:
raise KeyError('key %r already exists' % key)
super(StrictDict, self).__setitem__(key, value)
should more or less do it.
--
Steven
More information about the Python-list
mailing list