Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of Lists to List of Dictionaries

How can I convert a list of lists into a list of dictionaries?

More specifiicaly: How do I go from this:

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

to this:

[{'a1': None, 'b1': None, 'c1': None, 'd1': None, 'e1': None, 'f1': None, 'g1': None, 'h1': None, 'i1': None}, #etc
like image 441
LazySloth13 Avatar asked Nov 29 '22 02:11

LazySloth13


1 Answers

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,
   ...

This will work with any iterable of iterables, not just a list of lists (provided, of course, that the second-level elements are hashable).

In Python 2, the above code returns a list.

In Python 3, it returns an iterable. If you require a list, you could use list(map(dict.fromkeys, l)).

like image 186
NPE Avatar answered Dec 05 '22 13:12

NPE