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

时间:2019-06-07 13:28:50

标签: python list dictionary

我有两个嵌套列表:

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))

4 个答案:

答案 0 :(得分:6)

这里的问题是列表是不可散列的,所以您可以做的一件事是用itertools.chain来使列表扁平化,然后用字符串(这是 不可变)作为您当前使用的键(有关此主题的详细说明,请阅读here):

from itertools import chain

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

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

答案 1 :(得分:2)

如果您想手动进行操作(以了解示例算法),可以采用以下方法:

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

if len(list1) != len(list2):
    exit(-1)

res = {}
for index, content in enumerate(list1):
    res[content[0]] = list2[index]

print(res)

答案 2 :(得分:2)

另一个答案可能是:

list1 = [['s0'], ['s1'], ['s2']]
list2 = [['hello','world','the'],['as','per','the'],['assets','order']]
output_dict = {element1[0]: element2 for element1, element2 in zip(list1, list2)}

这种dict-comprehension的类似方式:

output_dict = {element1: element2 for [element1], element2 in zip(list1, list2)}

输出:

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

答案 3 :(得分:0)

首先存储匹配信息是一种奇怪的方法,但我会这样组合它们:

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

assert(len(list1) == len(list2))
output_dict = dict()
for index in range(len(list1)):
    output_dict[list1[index][0] = list2[index]

结果:

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

我假设变量s0,s1和s2是像第一个列表中那样的字符串。

相关问题