【问题标题】:List of Lists to List of Dictionaries字典列表的列表列表
【发布时间】:2013-03-13 08:19:50
【问题描述】:

如何将列表列表转换为字典列表?

更具体地说:我该如何做:

[['a1', 'b1', 'c1', 'd1', 'e1', 'f1', 'g1', 'h1', 'i1'], ['a2', 'b2', 'c2', 'd2', 'e2', 'f2', 'g2', 'h2', 'i2'], ['a3', 'b3', 'c3', 'd3', 'e3', 'f3', 'g3', 'h3', 'i3'], ['a4', 'b4', 'c4', 'd4', 'e4', 'f4', 'g4', 'h4', 'i4'], ['a5', 'b5', 'c5', 'd5', 'e5', 'f5', 'g5', 'h5', 'i5'], ['a6', 'b6', 'c6', 'd6', 'e6', 'f6', 'g6', 'h6', 'i6'], ['a7', 'b7', 'c7', 'd7', 'e7', 'f7', 'g7', 'h7', 'i7'], ['a8', 'b8', 'c8', 'd8', 'e8', 'f8', 'g8', 'h8', 'i8'], ['a9', 'b9', 'c9', 'd9', 'e9', 'f9', 'g9', 'h9', 'i9']]

到这里:

[{'a1': None, 'b1': None, 'c1': None, 'd1': None, 'e1': None, 'f1': None, 'g1': None, 'h1': None, 'i1': None}, #etc

【问题讨论】:

    标签: python list dictionary


    【解决方案1】:
    In [20]: l = [['a1', 'b1', 'c1', 'd1', 'e1', 'f1', 'g1', 'h1', 'i1'], ['a2', 'b2', 'c2', 'd2', 'e2', 'f2', 'g2', 'h2', 'i2'], ['a3', 'b3', 'c3', 'd3', 'e3', 'f3', 'g3', 'h3', 'i3'], ['a4', 'b4', 'c4', 'd4', 'e4', 'f4', 'g4', 'h4', 'i4'], ['a5', 'b5', 'c5', 'd5', 'e5', 'f5', 'g5', 'h5', 'i5'], ['a6', 'b6', 'c6', 'd6', 'e6', 'f6', 'g6', 'h6', 'i6'], ['a7', 'b7', 'c7', 'd7', 'e7', 'f7', 'g7', 'h7', 'i7'], ['a8', 'b8', 'c8', 'd8', 'e8', 'f8', 'g8', 'h8', 'i8'], ['a9', 'b9', 'c9', 'd9', 'e9', 'f9', 'g9', 'h9', 'i9']]
    
    In [21]: map(dict.fromkeys, l)
    Out[21]: 
    [{'a1': None,
      'b1': None,
      'c1': None,
      'd1': None,
      'e1': None,
      'f1': None,
      'g1': None,
      'h1': None,
      'i1': None},
     {'a2': None,
      'b2': None,
      'c2': None,
      'd2': None,
       ...
    

    这将适用于任何可迭代的可迭代对象,而不仅仅是列表列表(当然,前提是二级元素是 hashable)。

    在 Python 2 中,上述代码返回一个列表。

    在 Python 3 中,它返回一个可迭代对象。如果需要列表,可以使用list(map(dict.fromkeys, l))

    【讨论】:

    • 原谅我,因为我可能做错了一些非常基本的错误(因为这个答案有 19 位快乐的读者),但该代码似乎产生了错误:<map object at 0x02F3E210>。我做错了什么?
    • @Lewis:听起来您使用的是 Python 3。在这种情况下,请使用 list(map(dict.fromkeys, l))。我会更新答案。
    【解决方案2】:

    试试这个:

    l = [['a1', 'b1', 'c1', 'd1', 'e1', 'f1', 'g1', 'h1', 'i1'], ['a2', 'b2', 'c2', 'd2', 'e2', 'f2', 'g2', 'h2', 'i2'], ['a3', 'b3', 'c3', 'd3', 'e3', 'f3', 'g3', 'h3', 'i3'], ['a4', 'b4', 'c4', 'd4', 'e4', 'f4', 'g4', 'h4', 'i4'], ['a5', 'b5', 'c5', 'd5', 'e5', 'f5', 'g5', 'h5', 'i5'], ['a6', 'b6', 'c6', 'd6', 'e6', 'f6', 'g6', 'h6', 'i6'], ['a7', 'b7', 'c7', 'd7', 'e7', 'f7', 'g7', 'h7', 'i7'], ['a8', 'b8', 'c8', 'd8', 'e8', 'f8', 'g8', 'h8', 'i8'], ['a9', 'b9', 'c9', 'd9', 'e9', 'f9', 'g9', 'h9', 'i9']]
    res = []
    for line in l:
        res.append(dict((k, None) for k in line))
    

    或者:

    res = [dict((k, None) for k in line) for line in l]
    

    【讨论】:

      猜你喜欢
      • 2018-02-06
      • 2020-05-11
      • 2015-12-17
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 2013-04-06
      • 2011-04-21
      • 2021-03-17
      相关资源
      最近更新 更多