如何从两个嵌套列表制作字典?

Hem*_*tel 2 python dictionary list

我有两个嵌套列表:

list1 = [['s0'], ['s1'], ['s2']]
list2 = [['hello','world','the'],['as','per','the'],['assets','order']]
Run Code Online (Sandbox Code Playgroud)

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

d = {s0:['hello','world','the'],s1:['as','per','the'],s2:['assets','order']}
Run Code Online (Sandbox Code Playgroud)

输出应如下所示:

d = {s0:['hello','world','the'],s1:['as','per','the'],s2:['assets','order']}
Run Code Online (Sandbox Code Playgroud)

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

dict(zip(list1, list2))
Run Code Online (Sandbox Code Playgroud)

yat*_*atu 6

这里的问题是,列表是不哈希的,所以有一两件事你可以做的是扁平化你的清单itertools.chain,然后建立与字符串字典(这不可变的)作为键下面你目前的做法(读这里的一个更详细的解释关于这个主题):

from itertools import chain

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

{'s0': ['hello', 'world', 'the'],
 's1': ['as', 'per', 'the'],
 's2': ['assets', 'order']}
Run Code Online (Sandbox Code Playgroud)