python - 使用具有不同数量的键和值的两个列表创建嵌套字典
问题描述
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']}}
- 我有两个列表,keys和Values。
- “键”包含字典键,“值”包含键以及字典的值。
- output{} 是我想要作为输出的字典。
我实现了以下代码
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)
这个逻辑不起作用,有什么实现吗?
解决方案
您可以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']}
推荐阅读
- javascript - 在以前选择的同名单选按钮上调用函数
- java - 使用浏览器获取请求发送 JWT 令牌
- python - 循环数据帧
- c# - 从文本文件中查找行并使用 c# 将其复制到新的文本文件中
- hana - HANA:为什么时间戳列会截断毫秒并包含时区?
- jmeter - 我是 jmeter 新手,如何在 jmeter 中为 1000 个用户创建脚本
- python - 尝试通过按键输入更改视频帧
- python - 如何使用 .shp 文件生成与 tiff 文件大小相同的 RGB 图像?
- database - Sphinx RT 索引并按值在 json 中搜索
- reactjs - React 错误边界不能工作,只是打破