首页 > 解决方案 > 使用具有不同数量的键和值的两个列表创建嵌套字典

问题描述

Keys = ['a','b','c','d','e'] 
values = ['a','a1','a2','b','b4','b5','c','c4','c3','d','d4','d6','e','e4','e3']



output = {'a':{'a':['a1','a2'],'b':['b4','b5'],'c':['c4','c3'],'d':['d4','d6'],'e':['e4','e3']}}
          

我实现了以下代码

list4 = []

for i in range(len(values)):
    for j in range(len(Keys[1:])):
        if Keys[j]==values[i]:
            for k in range(i,len(values)):                
                list4.append(values[k])
                if Keys[j+1] == values[k]:
                    del list4[-1]
                    break

                        
            output = dict(zip(Keys[j], list4))
            print(output)

这个逻辑不起作用,有什么实现吗?

标签: pythonlistdictionary

解决方案


您可以itertools.groupby为此使用:

from itertools import groupby
Keys = ['a', 'b', 'c', 'd', 'e']
values = ['a', 'a1', 'a2', 'b', 'b4', 'b5', 'c', 'c4', 'c3',
          'c2', 'd', 'd4', 'd6', 'e', 'e4', 'e3']

di = {}
for k, g in groupby(values, key=lambda i: i[0]):
    di[k] = list(g)[1:]

# or with dict comprehension
# di = {k:list(g)[1:] for k, g in groupby(values, key=lambda i: i[0])}
print(di)
{'a': ['a1', 'a2'],
 'b': ['b4', 'b5'],
 'c': ['c4', 'c3', 'c2'],
 'd': ['d4', 'd6'],
 'e': ['e4', 'e3']}

推荐阅读