在python dict中获取和设置值的最佳习惯用法

Ben*_*end 7 python

我使用a dict作为短期缓存.我想从字典中获取一个值,如果字典中没有该键,则设置它,例如:

val = cache.get('the-key', calculate_value('the-key'))
cache['the-key'] = val
Run Code Online (Sandbox Code Playgroud)

'the-key'已经存在的情况下cache,第二行不是必需的.对此有更好,更短,更具表现力的习语吗?

Dar*_*mas 13

是的,使用:

val = cache.setdefault('the-key', calculate_value('the-key'))
Run Code Online (Sandbox Code Playgroud)

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}
Run Code Online (Sandbox Code Playgroud)

请参阅:http://docs.python.org/release/2.5.2/lib/typesmapping.html

  • 无论如何,这会计算`calculate_value('the-key')`. (5认同)
  • @eumiro,对。真可恶 我什至没有注意到-根据`calculate_value`可能很昂贵。 (2认同)

geo*_*org 12

可读性很重要!

if 'the-key' not in cache:
    cache['the-key'] = calculate_value('the-key')
val = cache['the-key']
Run Code Online (Sandbox Code Playgroud)

如果你真的喜欢单行:

val = cache['the-key'] if 'the-key' in cache else cache.setdefault('the-key', calculate_value('the-key'))
Run Code Online (Sandbox Code Playgroud)

另一种选择是__missing__在缓存类中定义:

class Cache(dict):
    def __missing__(self, key):
        return self.setdefault(key, calculate_value(key))
Run Code Online (Sandbox Code Playgroud)

  • 由于此答案并不总是计算缺失值,并且由于它提供了更多解决方案,因此它应该是公认的答案 (2认同)

Chr*_*tts 5

看一下Python Decorator库,更具体地说是Memoize,它充当缓存.这样你就可以calculate_value用Memoize装饰器装饰你的调用.