python - 列表列表到字典列表

标签 python list dictionary

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

更具体地说:我该怎么做:

[['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

最佳答案

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))

关于python - 列表列表到字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15380073/

相关文章:

python - 通过 python 浏览电子表格 xml

python - 如何按行读取数据并返回数据帧

Java 使用 Steams VS TreeMap 对 map 进行排序

python - 如何为字典的键和值指定类型提示?

python - 我怎样才能提高这个最短路径/捷径(数组图DS)解决方案的速度?

python - ctypes - 将带有指针的结构传递给另一个结构

Python:如何添加两个列表,其中与该键的值相同的键没有重复值?

python - 删除嵌套列表中的列时列表分配索引超出范围

python - Pandas :获取系列的前 10 个元素

python - “dict_keys”对象不支持索引