dictionary wart

Aloysio Figueiredo xpythonist at yahoo.com.br
Thu Mar 18 08:59:28 EST 2004


Why don't you extend the dict type to have your custom behaviour?

>>> class mydict(dict):
...   def __init__(self, args, default):
...     dict.__init__(self, args)
...     self._default = default
...   def __getitem__(self, item):
...     return self.get(item, self._default)
...
>>> x = mydict({'a' : 1, 'b' : 2}, 'default')
>>> x['a']
1
>>> x['b']
2
>>> x['foo']
'default'
>>>

 --- Jesper Olsen <jolsen at mail2world.com> escreveu: > Does python have
a way of defining a dictionary default? 
> I think not, but are there any plans to incorporate it?
> 
> Intuitively I would imagine that
> 
> a={}
> a.set_default(my_default)
> 
> would do this -ie. a[my_new_key] should now return the the default
> value my_default instead of creating an exception. This would be
> similar to how it is done in other languages, eg. Ruby:
> 
> a={}
> a.default=value
> 
> But surprisingly, in python set_default is a dictionary method used
> for looking up a key...
> 
> Jesper
> -- 
> http://mail.python.org/mailman/listinfo/python-list 

______________________________________________________________________

Yahoo! Mail - O melhor e-mail do Brasil! Abra sua conta agora:
http://br.yahoo.com/info/mail.html




More information about the Python-list mailing list