从list-object为dict创建密钥

时间:2013-10-27 17:14:38

标签: python dictionary

我有清单:

k = ["key1", "subkey2", "subsubkey3"]

我确信d是一个dict,d["key1"]["subkey2"]["subsubkey3"]有效。

如何将列表k转换为dict d的键,以便返回d[k[0]][k[1]]...

3 个答案:

答案 0 :(得分:9)

您可以尝试将reduce()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参数函数并连续地将它应用于列表的元素,从而累积结果。还有一个可选的初始值设定项参数,我们在这里使用了它。正如文档所述,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

在我们的情况下,我们传递的是initializer,因此它不会是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

在这种情况下,我们functiongetitem(a, b)(请参阅上面的链接),它只返回a[b]。此外,我们的iterablekinitializerd。因此,上面的reduce()调用相当于:

accum_value = d
for x in k:
    accum_value = accum_value[x]

答案 1 :(得分:3)

temp_d = d
for key in k:
 temp_d = temp_d[key]

在此代码完成后,temp_d将包含您的值

答案 2 :(得分:2)

这是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] 
相关问题