我有一个清单如下
['item1', 'item2', 'item3', 'item4']
我想从上面的列表构建一个字典,如下所示
{
"item1": {
"item2": {
"item3": "item4"
}
}
}
列表中的项目数是动态的。该字典将是一个嵌套字典,直到到达列表的最后一个元素。
python 有什么方法可以做到这一点吗?
简单的一行:
a = ['item1', 'item2', 'item3','item4']
print reduce(lambda x, y: {y: x}, reversed(a))
为了更好的理解,上面的代码可以扩展为:
def nest_me(x, y):
"""
Take two arguments and return a one element dict with first
argument as a value and second as a key
"""
return {y: x}
a = ['item1', 'item2', 'item3','item4']
rev_a = reversed(a) # ['item4', 'item3', 'item2','item1']
print reduce(
nest_me, # Function applied until the list is reduced to one element list
rev_a # Iterable to be reduced
)
# {'item1': {'item2': {'item3': 'item4'}}}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)