Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

I use a dict as a short-term cache. I want to get a value from the dictionary, and if the dictionary didn't already have that key, set it, e.g.:

val = cache.get('the-key', calculate_value('the-key'))
cache['the-key'] = val

In the case where 'the-key' was already in cache, the second line is not necessary. Is there a better, shorter, more expressive idiom for this?

like image 895
Benjamin Wohlwend Avatar asked Jun 22 '12 08:06

Benjamin Wohlwend


2 Answers

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))
like image 74
georg Avatar answered Oct 05 '22 17:10

georg


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

like image 42
Daren Thomas Avatar answered Oct 05 '22 15:10

Daren Thomas