views:

305

answers:

2

I'm using all of them to print the names of assigned IANA values in a packet. So all of the dictionaries have the same default value "RESERVED".

I don't want to use d.get(key,default) but access dictionaries by d[key] so that if the key is not in d, it returns the default (that is same for all dictionaries).

I do not necessarily need to use dictionaries, but they were the intuitive choice... Also, a dictionary where I could do this

d = {
   1..16 = "RESERVED",
   17 : "Foo",
   18 : "Bar,
   19..255: "INVALID"
  }

Would be the preferred solution

Tuples could be another alternative, but then I'm prone to offset errors assigning the values... (and my code would not be "human readable")

Oh yeah, Python 2.4

+8  A: 

If you can migrate to Python 2.5, there is the defaultdict class, as shown here. You can pass it an initializer that returns what you want. Otherwise, you'll have to roll your own implementation of it, I fear.

Mario
If upgrade was an option, I would go for 3.0 altogether, sadly I think I'm stuck with 2.4 so I can run this on EL5 w/o installing a new python...
Kimvais
There is a defaultdict backport http://code.activestate.com/recipes/523034/
Peter Hoffmann
And a very clean one. Quite interesting to understand the defaultdict implementation.
e-satis
+3  A: 

If you can, use Mario's solution.

If you can't, you just have to subclass a dictionary-like object. Now, you can do that by inheriting directly from "dict", it will be fast and efficient. For old Python versions, with which you can't inherit from "dict", there is "UserDict", a pure Python dictionary implementation.

With it, you would do it this way :

#!/usr/bin/env python
# -*- coding= UTF-8 -*-

import UserDict

class DefaultDict(UserDict.UserDict) :

    default_value = 'RESERVED'

    def __getitem__(self, key) :
        return self.data.get(key, DefaultDict.default_value)


d = DefaultDict()
d["yes"] = True;
print d["yes"]
print d["no"]

Keep in mind that "UserDict" is slower than "dict".

e-satis
I have to go with this approach (looks like 2.4 can include dict so I am not completely lost)... However now I started wondering whether it would be possible create a dictionary-like class that allowed the 'range' assignments.
Kimvais
What do you mean by range assignment ?
e-satis
That should be `self.default_value`, so it functions correctly with subclassing.
Aaron Gallagher
There are a 10 000 things you can improve this snippet. This is just an illustration. A bullet proof code would be http://code.activestate.com/recipes/523034/
e-satis