如何以 pythonic 方式将 python 列表转换为嵌套字典
How to Convert python list into nested dictionaries in pythonic way
我是 python 的新手,正在尝试将我的输入列表 ["a", "b", "c"]
转换为嵌套词典,例如 {"a":{"b":{"c":{}}}}
您可能不应该在生产中使用它,但它很有趣...
def make_dict_from_list(li):
temp = output = {}
for i, e in enumerate(li, 1):
if i != len(li):
temp[e] = {}
temp = temp[e]
else:
temp[e] = []
return output
print(make_dict_from_list(['a']))
print(make_dict_from_list(['a', 'b', 'c']))
产出
{'a': []}
{'a': {'b': {'c': []}}}
我是 python 的新手,正在尝试将我的输入列表 ["a", "b", "c"]
转换为嵌套词典,例如 {"a":{"b":{"c":{}}}}
您可能不应该在生产中使用它,但它很有趣...
def make_dict_from_list(li):
temp = output = {}
for i, e in enumerate(li, 1):
if i != len(li):
temp[e] = {}
temp = temp[e]
else:
temp[e] = []
return output
print(make_dict_from_list(['a']))
print(make_dict_from_list(['a', 'b', 'c']))
产出
{'a': []}
{'a': {'b': {'c': []}}}