Custom dict to prevent keys from being overridden

Discussion in 'Python' started by Julien, Aug 28, 2011.

  1. Julien

    Julien Guest

    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
    Julien, Aug 28, 2011
    #1
    1. Advertising

  2. 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
    Steven D'Aprano, Aug 28, 2011
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Menghan Zheng
    Replies:
    1
    Views:
    264
    alex23
    Apr 20, 2010
  2. Cameron Simpson
    Replies:
    6
    Views:
    342
    alex23
    Apr 21, 2010
  3. Ethan Furman

    Python 3: dict & dict.keys()

    Ethan Furman, Jul 24, 2013, in forum: Python
    Replies:
    4
    Views:
    198
    Steven D'Aprano
    Jul 25, 2013
  4. Peter Otten

    Re: Python 3: dict & dict.keys()

    Peter Otten, Jul 24, 2013, in forum: Python
    Replies:
    1
    Views:
    85
    Neil Cerutti
    Jul 24, 2013
  5. Oscar Benjamin

    Re: Python 3: dict & dict.keys()

    Oscar Benjamin, Jul 24, 2013, in forum: Python
    Replies:
    0
    Views:
    98
    Oscar Benjamin
    Jul 24, 2013
Loading...

Share This Page