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

Nik*_*dra 0 python dictionary list

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

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

[45, 32] # Normal list

{(1, 3, 5): 45, (4, 6, 9): 32} # The dictionary
Run Code Online (Sandbox Code Playgroud)

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

dictionary = dict(zip(l1, l2)))
print(dictionary)
Run Code Online (Sandbox Code Playgroud)

Ble*_*der 6

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

TypeError: unhashable type: 'list'
Run Code Online (Sandbox Code Playgroud)

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

以下将有效:

dict(zip(map(tuple, l1), l2)))
Run Code Online (Sandbox Code Playgroud)

或者更清楚:

{tuple(k): v for k, v in zip(l1, l2)}
Run Code Online (Sandbox Code Playgroud)