将列表列表转换为词典列表 [英] Convert list of lists to list of dictionaries

查看:44
本文介绍了将列表列表转换为词典列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将列表列表转换为词典列表.我有办法做到,但我怀疑还有更好的办法:

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]

有输出

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

这可以通过循环来完成,但是我敢打赌,有一个函数可以使它更容易实现.来自此答案,我猜测有一种解决方法 map 命令,但是我不太确定该怎么做.

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.

推荐答案

您可以将列表理解与 dict() 构造函数和

You can use list comprehension with the dict() constructor and zip:

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

演示

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

这篇关于将列表列表转换为词典列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆