繁体   English   中英

将列表转换为嵌套字典

[英]Convert a list into a nested Dict

我需要将列表转换为 python 中的嵌套字典。 像这样:

list = [1, 2, 3, 3, 4]
value = 5

转换为:

dict = {1: {2: {3: {4: 5}}}}

我已经试过了

new_dict = current = {}
for number in list:
   current[number] = {}
   current = current[number]   

但是你怎么能看到这个值不在字典中。 我该如何解决?

编辑:更改变量名称和关键字

  1. 不确定使用什么valuenew_dict

  2. 永远不要使用内置类型命名变量(不要使用list

  3. 对于每个数字,您正在创建一个空字典,然后将current重新分配给它

    基本上current[1]={}后跟current=current[1]显然总是以current={}结尾

一种方法:

myList = [1, 2, 3, 4]   

首先使用myListvalue中的最后一个元素创建最里面的字典

current_dict = {myList[-1]: value}   

new_dict = {}  

现在遍历列表反向中的每个数字,不包括第一个数字(3,2,1)

for number in myList[::-1][1:]:
    new_dict[number] = current_dict
    current_dict = new_dict
    new_dict = {}

这看起来像这样:

new_dict[3] = {4:5}           | current_dict ={3:{4:5}} 
new_dict[2] = {3:{4:5}}       | current_dict ={2:{3:{4:5}}}
new_dict[1] = {{2:{3:{4:5}}}  | current_dict ={1:{2:{3:{4:5}}}}

current_dict会有最终结果

print(current_dict)   #{1: {2: {3: {4: 5}}}}

一种方法:

value = 5
my_dict = {}
my_list = [1, 2, 3, 3, 4]
for e in reversed(my_list):
    if not e in my_dict:
        my_dict = {e:value}
        value = {e:value}

打印(我的字典):

{1: {2: {3: {4: 5}}}}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM