Assuming your list of lists is stored in variable l, you can use the following for loop to construct the desire dictionary with a dictionary mapping p to keep track of the parent node for each key:d = {}p = {}for k, *s in l: r = p.get(k, d)[k] = {i: {} for i in s} p.update({i: r for i in s}) d将变为:{'A': {'A1': {'B': {'B1': {'b1': {}, 'b2': {}, 'b3': {}}, 'B2': {'d1': {}, 'd2': {}, 'd3': {}, 'd4': {}}}, 'C': {'C1': {'a1': {}, 'a2': {}, 'a3': {}}, 'C2': {'n1': {}, 'n2': {}, 'n3': {}, 'n4': {}}, 'C3': {'x1': {}, 'x2': {}, 'x3': {}, 'x4': {}}}}}}要使叶节点成为列表,可以从下至上遍历树,并使用集合m跟踪子节点,以便可以使用集合差异找到要添加到子节点的所有顶部节点.最后是主词典d:To make leaf nodes a list, you can traverse the tree from the bottom up and use a set m to keep track of the child nodes so that you can use set difference to find all the top nodes to add to the main dictionary d in the end:p = {}m = set()while l: k, *s = l.pop() p[k] = {i: p[i] for i in s} if all(i in p for i in s) else s m.update(s)d = {i: p[i] for i in p.keys() - m} d将变为:{'A': {'A1': {'B': {'B1': ['b1', 'b2', 'b3'], 'B2': ['d1', 'd2', 'd3', 'd4']}, 'C': {'C1': ['a1', 'a2', 'a3'], 'C2': ['n1', 'n2', 'n3', 'n4'], 'C3': ['x1', 'x2', 'x3', 'x4']}}}} 这篇关于嵌套列表中的嵌套字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-14 06:26