我有清单:
k = ["key1", "subkey2", "subsubkey3"]
我确定这d是一个d["key1"]["subkey2"]["subsubkey3"]有效的字典。
如何将 list 转换k为 dict 的键d以便返回d[k[0]][k[1]]...?
我有清单:
k = ["key1", "subkey2", "subsubkey3"]
我确定这d是一个d["key1"]["subkey2"]["subsubkey3"]有效的字典。
如何将 list 转换k为 dict 的键d以便返回d[k[0]][k[1]]...?
您可以尝试使用reduce()with operator.getitem:
>>> from operator import getitem
>>>
>>> d = {'key1': {'subkey2': {'subsubkey3': 'value'}}}
>>> k = ["key1", "subkey2", "subsubkey3"]
>>>
>>> reduce(getitem, k, d)
'value'
在 Python 3.x 中,您应该使用functools.reduce().
reduce()简单地接受一个 2-argument 函数并将其连续应用于列表的元素,累积结果。还有一个可选的初始化参数,我们在这里使用过。正如文档所述,reduce()大致相当于:
def reduce(function, iterable, initializer=None):
it = iter(iterable)
if initializer is None:
try:
initializer = next(it)
except StopIteration:
raise TypeError('reduce() of empty sequence with no initial value')
accum_value = initializer
for x in it:
accum_value = function(accum_value, x)
return accum_value
在我们的例子中,我们传递的是 aninitializer所以它不会是None。因此,我们拥有的是:
def reduce(function, iterable, initializer=None):
it = iter(iterable)
accum_value = initializer
for x in it:
accum_value = function(accum_value, x)
return accum_value
我们function在这种情况下是getitem(a, b)(见上面的链接),它只返回a[b]. 此外, our iterableisk和 our initializeris d。所以reduce()上面的调用相当于:
accum_value = d
for x in k:
accum_value = accum_value[x]
temp_d = d
for key in k:
temp_d = temp_d[key]
此代码完成后 temp_d 将包含您的值
这是少数几个reduce可能是个好主意的情况之一——它所做的是连续对一个值应用相同的操作。
items = {'foo': {'bar': {'baz': 123}}}
keys = ['foo', 'bar', 'baz']
reduce(lambda d, k: d[k], keys, items)
这相当于:
items = {'foo': …}
keys = ['foo', …]
result = items
for k in keys:
# The RHS here is the function passed to reduce(), applied to the
# (intermediate) result and the current step in the loop
result = items[k]