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

时间:2021-06-12 04:13:53

标签: python python-3.x list dictionary

假设我有以下三个列表:

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}
]

在语法上最简洁的方法是什么?

感谢您的帮助!!

3 个答案:

答案 0 :(得分:12)

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

答案 1 :(得分:8)

尝试使用 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)]

输出

[
    {'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}
]

答案 2 :(得分:4)

这类似于@Tim Roberts 解决方案,但允许任意输入。

[dict(((type(x).__name__,x) for x in (a,b,c))) for a,b,c in zip(list_1,list_2,list_3)]