dictionary wart

Fuzzyman michael at foord.net
Thu Mar 18 10:20:44 EST 2004


On Thu, 18 Mar 2004 15:06:48 +0000, Fuzzyman <michael at foord.net>
wrote:

>On Thu, 18 Mar 2004 13:46:19 GMT, Jesper <jolsen at mail2world.com>
>wrote:
>
>>Paul Rubin wrote:
>>> jolsen at mail2world.com (Jesper Olsen) writes:
>>> 
>>>>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. 
>>> 
>>> 
>>> No, instead of a[my_new_key] use a.get(my_new_key, my_default).
>>> That does what you want.
>>
>>Unfortunately not - get() is different, because you can not assign to it.
>>For instance in a dictionary which is mapping strings to integers (or 
>>lists), I would like to do
>>
>>a[my_key]+=5
>>
>>expressing that with get() would be awkward.
>>
>>Jesper
>
>You can however subclass dict to create something that *behaves* like
>a dictionary, but for unknown keys returns a default :
>
>Regards,
>
>Fuzzy
>
>http://www.voidspace.org.uk/atlantibots/pythonutils.html
>
>e.g. (untested - but should work)
>
>
>class defaultDict(dict):
>    """A dictionary that returns a default for non-existent keys.
>    Won't work for methods like pop unless you also define them as
>well."""
>    def __init__(self, default):
>        dict.__init__(self)
>        self.default = default
>
>    def __getitem__(self, item):
>        if self.has_key(item):
>            return dict.__getitem__(self, key) 
>        else:
>            return self.default
>

Oops - that would be (and I see that someone else already suggested
this anyway )...

            return dict.__getitem__(self, item) 


>if __name__ == '__main__':
>    a = defaultDict(3)
>    a['test'] = 4
>    print a['test']
>    print a['fish']
>
>
>
>
>---
>Everyone has talent. What is rare is the courage to follow talent to the dark place where it leads. -Erica Jong
>Ambition is a poor excuse for not having sense enough to be lazy. -Milan Kundera 
>
>http://www.voidspace.org.uk 
>Where Headspace Meets Cyberspace
>Cyberpunk and Science Resource Site
>Exploring the worlds of Psychology, Spirituality, Science and Computing

---
Everyone has talent. What is rare is the courage to follow talent to the dark place where it leads. -Erica Jong
Ambition is a poor excuse for not having sense enough to be lazy. -Milan Kundera 

http://www.voidspace.org.uk 
Where Headspace Meets Cyberspace
Cyberpunk and Science Resource Site
Exploring the worlds of Psychology, Spirituality, Science and Computing
--
http://www.fuchsiashockz.co.uk
http://groups.yahoo.com/group/void-shockz
http://www.learnlandrover.com



More information about the Python-list mailing list