首页 > 解决方案 > 如何从两个嵌套列表中制作字典?

问题描述

我有两个嵌套列表:

list1 = [['s0'], ['s1'], ['s2']]
list2 = [['hello','world','the'],['as','per','the'],['assets','order']]

我想从这些列表中创建一个字典,其中的键list1和值来自list2

d = {s0:['hello','world','the'],s1:['as','per','the'],s2:['assets','order']}

输出应如下所示:

d = {s0:['hello','world','the'],s1:['as','per','the'],s2:['assets','order']}

list1如果是普通(非嵌套)列表,则以下代码有效。list1但是当是嵌套列表时它不起作用。

dict(zip(list1, list2))

标签: pythonlistdictionary

解决方案


这里的问题是列表不是可散列的,因此您可以做的一件事是使用当前方法将字符串(不可itertools.chain变)作为键构建字典(阅读此处以获取更详细的说明)关于这个话题):

from itertools import chain

dict(zip(chain.from_iterable(list1),list2))

{'s0': ['hello', 'world', 'the'],
 's1': ['as', 'per', 'the'],
 's2': ['assets', 'order']}

推荐阅读