擅长:python、mysql、java
<p>还要看一下collections模块的defaultdict类。这是一个dict,您可以指定在找不到密钥时必须返回的内容。有了它,你可以做如下事情:</p>
<pre><code>class MyDefaultObj:
def __init__(self):
self.a = 1
from collections import defaultdict
d = defaultdict(MyDefaultObj)
i = d['NonExistentKey']
type(i)
<instance of class MyDefalutObj>
</code></pre>
<p>它允许你使用熟悉的d[i]约定。</p>
<p>不过,正如mikej所说,.get()也可以工作,但下面的表单更接近于JavaScript示例:</p>
<pre><code>d = {}
i = d.get('NonExistentKey') or MyDefaultObj()
# the reason this is slightly better than d.get('NonExistent', MyDefaultObj())
# is that instantiation of default value happens only when 'NonExistent' does not exist.
# With d.get('NonExistent', MyDefaultObj()) you spin up a default every time you .get()
type(i)
<instance of class MyDefalutObj>
</code></pre>