【问题标题】:How do I create a list of dictionaries with same keys?如何创建具有相同键的字典列表?
【发布时间】:2021-06-12 04:13:53
【问题描述】:

假设我有以下三个列表:

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

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

感谢您的帮助!!

【问题讨论】:

    标签: python python-3.x list dictionary


    【解决方案1】:
    dct = [{'int':a,'str':b,'float':c}  for a,b,c in zip(list_1,list_2,list_3)]
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

        这类似于@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)]
        

        【讨论】:

          猜你喜欢
          • 2019-03-12
          • 2021-12-07
          • 2018-10-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-10-05
          • 2019-11-19
          相关资源
          最近更新 更多