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

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to