擅长:python、mysql、java
<p>以前没有提到过的解决方案是</p>
<pre><code>dictget = lambda d, *k: [d[i] for i in k]
</code></pre>
<p>然后使用它:</p>
<pre><code>key_1, key_2 = dictget(d, 'key_1', 'key_2')
</code></pre>
<p>它的优点是,即使需要检索更多的变量,它也是非常可读的。</p>
<p>然而,更具可读性的是“真实的”函数,如</p>
<pre><code>def dictget(d, *k):
"""Get the values corresponding to the given keys in the provided dict."""
return [d[i] for i in k]
# or maybe
return (d[i] for i in k) # if we suppose that we have bigger sets of result
# or, equivalent to this
for i in k:
yield d[i]
</code></pre>
<p>它还支持使用docstring进行注释,并且是首选。</p>