擅长:python、mysql、java
<p>简单递归方法:</p>
<pre><code>def function(keys, dct):
return not keys or (keys[0] in dct and function(keys[1:], dct[keys[0]]))
>>> function(keys1, dct) # never shadow built-in names
True
>>> function(keys2, dct)
True
>>> function(keys3, dct)
False
</code></pre>
<p>这假设了一个非常统一的结构:所有中间值都是dict本身,深度总是至少是键的长度。否则,您需要处理一些错误:</p>
<pre><code>def function(keys, dct):
try:
return not keys or function(keys[1:], dct[keys[0]])
except (TypeError, KeyError): # this allows you to shorten the above
return False
</code></pre>