Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Custom dict to prevent keys from being overridden

Reply
Thread Tools

Custom dict to prevent keys from being overridden

 
 
Julien
Guest
Posts: n/a
 
      08-28-2011
Hi,

With a simple dict, the following happens:

>>> d = {

.... 'a': 1,
.... 'b': 2,
.... 'a': 3
.... }
>>> d

{'a': 3, 'b': 2}

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

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?

Many thanks!

Kind regards,

Julien
 
Reply With Quote
 
 
 
 
Steven D'Aprano
Guest
Posts: n/a
 
      08-28-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

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: dict.keys() and dict.values() are always the same order, is it? Cameron Simpson Python 6 04-21-2010 04:37 AM
dict.keys() and dict.values() are always the same order, is it? Menghan Zheng Python 1 04-20-2010 03:51 AM
Datagrid CssClass being overridden by TD style Laurence Neville ASP .Net 4 09-23-2004 09:59 AM
Datagrid CssClass being overridden by TD style Laurence Neville ASP .Net Datagrid Control 2 09-22-2004 01:46 PM
Re: dict->XML->dict? Or, passing small hashes through text? Skip Montanaro Python 0 08-15-2003 03:46 PM



Advertisments