【发布时间】:2013-09-05 19:22:29
【问题描述】:
我想使用键列表遍历多维字典。最后一个键,我会返回值。
我会得到一个列表,它会映射到字典的键,但我不知道我需要走多远。换句话说,我不会事先知道键列表中有多少项。
这就是我想出的。有没有更优雅的方式来做到这一点?
在我的示例中,walk_to_value() 将返回“三个值”:
d = {'one': {'two': {'three': 'the three value'}}}
l = ['one','two','three']
def walk_to_value(d, l):
e = l.pop(0)
d1 = d[e]
if (type(d1) == dict):
return walk_to_value(d1, l)
else:
return d1
print walk_to_value(d, l)
【问题讨论】:
-
不要使用
type,而是使用if isinstance(d1, dict):。这更加健壮,因为它还将包含从 dict 继承的对象。
标签: python list recursion dictionary multidimensional-array