简体   繁体   English

将列表列表转换为字典列表

[英]Convert list of lists to list of dictionaries

I want to convert a list of lists to a list of dictionaries.我想将列表列表转换为字典列表。 I have a way to do it but I suspect there's a better way:我有办法做到这一点,但我怀疑有更好的方法:

t = [[1,2,3], [4,5,6]]
keys = ['a', 'b', 'c']
[{keys[0]:l[0], keys[1]:l[1], keys[2]:l[2]} for l in t]

with output带输出

[{'a': 1, 'c': 3, 'b': 2}, {'a': 4, 'c': 6, 'b': 5}]

This could be done with a loop, but I bet there's a function to do it even easier.这可以通过循环来完成,但我敢打赌有一个函数可以更容易地做到这一点。 From this answer I'm guessing there's a way to do it with the map command, but I'm not quite sure how.这个答案我猜有一种方法可以使用map命令来做到这一点,但我不太确定如何。

You can use list comprehension with the dict() constructor and zip :您可以将列表推导与dict()构造函数和zip

[dict(zip(keys, l)) for l in t ]

Demo演示

>>> d = [dict(zip(keys, l)) for l in t ]
>>>
>>> d
[{'a': 1, 'c': 3, 'b': 2}, {'a': 4, 'c': 6, 'b': 5}]
>>> 

It can also be solved with a dictionary comprehension, this way:它也可以通过字典理解来解决,这样:

>>> [{k:v for k,v in zip(keys, l)} for l in t]
[{'c': 3, 'b': 2, 'a': 1}, {'c': 6, 'b': 5, 'a': 4}]

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

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