简体   繁体   English

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

[英]Combining nested list and normal list into a dictionary

Let's say I have two lists, where one is a nested list and the other is a normal list, how do I combine them into a dictionary? 假设我有两个列表,其中一个是嵌套列表,另一个是普通列表,如何将它们组合成字典?

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

[45, 32] # Normal list

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

I tried this but it gives me an error, 我试过了,但这给我一个错误,

dictionary = dict(zip(l1, l2)))
print(dictionary)

The error you got was probably something like this: 您收到的错误可能是这样的:

TypeError: unhashable type: 'list'

[1, 3, 5] and (1, 3, 5) are not the same. [1, 3, 5](1, 3, 5)不同。 Tuples are immutable and therefore can be used as dictionary keys, but lists cannot because they can be modified. 元组是不可变的,因此可以用作字典键,但是列表不能修改,因为它们可以被修改。

The following will work: 以下将起作用:

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

Or more clearly: 或者更清楚地:

{tuple(k): v for k, v in zip(l1, l2)}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM