In Python it is possible to read a dictionary/hash key while at the same time setting the key to a default value if one does not already exist.
For example:
There is no equivalent to this function in Python. You can always use monkey patching to get this functionality:
class Hash
def setdefault(key, value)
if self[key].nil?
self[key] = value
else
self[key]
end
end
end
h = Hash.new
h = { 'key' => 'value' }
h.setdefault('key', 'default')
# => 'value'
h.setdefault('key-doesnt-exist', 'default')
# => 'default'
But keep in mind that monkey patching is often seen as a taboo, at least in certain code environments.
The golden rule of monkey patching applies: just because you could, doesn’t mean you should.
The more idiomatic way is to define default values through the Hash constructor by passing an additional block or value.