Best idiom to get and set a value in a python dict

yes, use:

val = cache.setdefault('the-key', calculate_value('the-key'))

An example in the shell:

>>> cache = {'a': 1, 'b': 2}
>>> cache.setdefault('a', 0)
1
>>> cache.setdefault('b', 0)
2
>>> cache.setdefault('c', 0)
0
>>> cache
{'a': 1, 'c': 0, 'b': 2}

See: http://docs.python.org/release/2.5.2/lib/typesmapping.html


Readability matters!

if 'the-key' not in cache:
    cache['the-key'] = calculate_value('the-key')
val = cache['the-key']

If you really prefer an one-liner:

val = cache['the-key'] if 'the-key' in cache else cache.setdefault('the-key', calculate_value('the-key'))

Another option is to define __missing__ in the cache class:

class Cache(dict):
    def __missing__(self, key):
        return self.setdefault(key, calculate_value(key))

Tags:

Python