Dmex
Dmex

Reputation: 1

Convert lists of list into List of dictionaries

I want to convert this list of lists to list of dictionaries as the following format using python3.

[['a','b','c'],['d','e'],['f','g']]

The value to key need to be 1 for all list elements. Any guide please.

[{'a':1,'b':1,'c':1},{'d':1,'e':1},{'f':1,'g':1}]

Upvotes: 0

Views: 45

Answers (1)

robbo
robbo

Reputation: 545

You can do this in a single line using a combination of list and dictionary comprehension. Assume a is your original list:

a = [['a','b','c'],['d','e'],['f','g']]

The you would get your desired output with:

b = [{k: 1 for k in i} for i in a]

Upvotes: 2

Related Questions