471,336 Members | 1,423 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,336 software developers and data experts.

Making static dicts?

Hello!

Just to ask, is it possible to make a static dictionary in python. So
that the keys in the dictionary cannot be removed, changed or new ones
added, but the value pairs can.

Is this possible with python?

thanks,

Ognjen.

Jun 18 '07 #1
2 8326
On Jun 18, 1:46 pm, Ognjen Bezanov <Ogn...@mailshack.comwrote:
Hello!

Just to ask, is it possible to make a static dictionary in python. So
that the keys in the dictionary cannot be removed, changed or new ones
added, but the value pairs can.

Is this possible with python?

thanks,

Ognjen.
How much functionality do you need? Something like this might work
(though it could use better error messages.

Expand|Select|Wrap|Line Numbers
  1. class StaticDict:
  2. def __init__(self,srcdict):
  3. self._srcdict = srcdict
  4. def __getitem__(self,idx):
  5. return self._srcdict[idx]
  6.  
Use it like this:
>>sd = StaticDict({'a':'b'})
sd['a']
'b'
>>sd['b']
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 5, in __getitem__
KeyError: 'b'
>>sd['a'] = "hello"
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: StaticDict instance has no attribute '__setitem__'
>>>
Jun 18 '07 #2
On Mon, 18 Jun 2007 21:46:23 +0100, Ognjen Bezanov wrote:
Hello!

Just to ask, is it possible to make a static dictionary in python. So
that the keys in the dictionary cannot be removed, changed or new ones
added, but the value pairs can.

Is this possible with python?

I'm sure it is possible, but you'll have to program it yourself.

The usual term for what you are describing is "immutable" rather than
static. For some ways of making an immutable class, see here:

http://northernplanets.blogspot.com/...in-python.html

To get the dictionary behaviour, the easiest ways would be either to
sub-class from dict:

class ImmutableDict(dict):
pass

or perhaps use delegation (google on "Python automatic delegation" for
more information).

You might like to look at the source code for the UserDict module in the
standard library for some ideas (especially the DictMixin class).

I leave putting these pieces together into a working immutable dictionary
up to you. Good luck!
--
Steven.

Jun 18 '07 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

4 posts views Thread by John Townsend | last post: by
reply views Thread by rosydwin | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.