如何创建具有相同键的字典列表?

假设我有以下三个列表:

list_1 = [1, 2, 3, 4, 5]
list_2 = ['a', 'b', 'c', 'd', 'e']
list_3 = [1.1, 2.2, 3.3, 4.4]

如何将这三个列表组合成这样:

[
    {'int': 1, 'str': 'a', 'float': 1.1}, 
    {'int': 2, 'str': 'b', 'float': 2.2}, 
    {'int': 3, 'str': 'c', 'float': 3.3}, 
    {'int': 4, 'str': 'd', 'float': 4.4}, 
    {'int': 5, 'str': 'e', 'float': 5.5}
]
[
    {'int': 1, 'str': 'a', 'float': 1.1}, 
    {'int': 2, 'str': 'b', 'float': 2.2}, 
    {'int': 3, 'str': 'c', 'float': 3.3}, 
    {'int': 4, 'str': 'd', 'float': 4.4}, 
    {'int': 5, 'str': 'e', 'float': 5.5}
]

实现此目的的语法最干净的方法是什么?

谢谢你的帮助!!

回答

dct = [{'int':a,'str':b,'float':c}  for a,b,c in zip(list_1,list_2,list_3)]


回答

尝试使用zip().

它基本上遍历
[(1, 'a', 1.1), (2, 'b', 2.2), (3, 'c', 3.3), (4, 'd', 4.4), (5, 'e', 5.5)],将它与您的键配对,["int","str","float"]并用它创建一个字典列表。

袖珍的

dictList = [{k:v for k,v in zip(['int','str','float'],pair)} for pair in zip(list_1,list_2,list_3)]

人眼可读

dictList = []
for pair in zip(list_1,list_2,list_3):
    dicts1 = {}
    for k,v in zip(['int','str','float'],pair):
        dicts1[k] = v
    dictList.append(dicts1)

硬编码一点

dictList = [{'int':x,'str':y,'float':z} for x,y,z in zip(list_1,list_2,list_3)]

输出


以上是如何创建具有相同键的字典列表?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>