将嵌套列表和普通列表组合到字典中

问题描述 投票:0回答:1

假设我有两个列表,其中一个是嵌套列表,另一个是普通列表,如何将它们组合成字典?

[[1, 3, 5], [4, 6, 9]] # Nested list

[45, 32] # Normal list

{(1, 3, 5): 45, (4, 6, 9): 32} # The dictionary

我试过这个,但它给了我一个错误,

dictionary = dict(zip(l1, l2)))
print(dictionary)
python list dictionary
1个回答
6
投票

你得到的错误可能是这样的:

TypeError: unhashable type: 'list'

[1, 3, 5](1, 3, 5)不一样。元组是不可变的,因此可以用作字典键,但列表不能,因为它们可以被修改。

以下将有效:

dict(zip(map(tuple, l1), l2)))

或者更清楚:

{tuple(k): v for k, v in zip(l1, l2)}
© www.soinside.com 2019 - 2024. All rights reserved.