Friday, September 2, 2005

getdefault method for python dictionary

In this blog:

Blogger says that Python's dictionary method, 'setdefault' without explicit default
is confusing and useless. Now I think there should be a 'getdefault' method
which also requires two explicit arguments, it will return explicit default
if no key exists.

Here is an example:

>>> d = {1: None}
>>> print d.getdefault(1, 'Hi')
>>> print d.getdefault(2, 'Hi')

Hmm.. there is already a 'get' method. If we have 'getdefault'
then 'get' can be deprecated, Here is the reason:

>>> d = {1: None}
>>> print d.get(1)
>>> print d.get(2)

See, here I didn't thought about any use cases.