Nag*_*hmi 3 python dictionary list python-2.7
我有一个如下列表
['item1', 'item2', 'item3', 'item4']
Run Code Online (Sandbox Code Playgroud)
我想从上面的列表中构建一个字典,如下所示
{
"item1": {
"item2": {
"item3": "item4"
}
}
}
Run Code Online (Sandbox Code Playgroud)
列表中的项目数是动态的.字典将是嵌套字典,直到它到达列表的最后一个元素.有没有办法在python中做到这一点?
简单的单线程:
a = ['item1', 'item2', 'item3','item4']
print reduce(lambda x, y: {y: x}, reversed(a))
Run Code Online (Sandbox Code Playgroud)
为了更好地理解,上面的代码可以扩展为:
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'}}}
Run Code Online (Sandbox Code Playgroud)
使用递归:
def list2dict(src_list):
if len(src_list) > 1:
return {src_list[0] : list2dict(src_list[1:])}
return src_list[0]
Run Code Online (Sandbox Code Playgroud)
输出:
>>> list2dict(['item1', 'item2', 'item3', 'item4'])
{'item1': {'item2': {'item3': 'item4'}}}
Run Code Online (Sandbox Code Playgroud)