Custom dict to prevent keys from being overridden

J

Julien

Hi,

With a simple dict, the following happens:
.... 'a': 1,
.... 'b': 2,
.... 'a': 3
.... }{'a': 3, 'b': 2}

.... i.e. the value for the 'a' key gets overridden.

What I'd like to achieve is:
.... 'a': 1,
.... 'b': 2,
.... 'a': 3
.... }
Error: The key 'a' already exists.

Is that possible, and if so, how?

Many thanks!

Kind regards,

Julien
 
S

Steven D'Aprano

Julien said:
What I'd like to achieve is:

... '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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top