How to create a dictionary out of a list of lists in python?

  • A+
Category:Languages

Let's suppose I have the following list made out of lists

list1 = [['a','b'],['a'],['b','c'],['c','d'],['b'], ['a','d']] 

I am wondering if there is a way to convert every element of list1 in a dictionary where all the new dictionaries will use the same key. E.g: if ['a'] gets to be {'a':1}, and ['b'] gets to be {'b':2}, I would like for all keys a the value of 1 and for all keys b the value of 2. Therefore, when creating the dictionary of ['a','b'], I would like to turn into {'a':1, 'b':2}.

What I have found so far are ways to create a dictionary out of lists of lists but using the first element as the key and the rest of the list as the value:

Please note that's not what I am interested in. The result I would want to obtain from list1 is something like:

dict_list1 = [{'a':1,'b':2}, {'a':1}, {'b':2,'c':3}, {'c':3,'d':4}, {'b':2}, {'a':1,'d':4}] 

I am not that interested in the items being that numbers but in the numbers being the same for each different key.

 


Using chain and OrderedDict you can do auto mapping

from itertools import chain from collections import OrderedDict  list1 = [['a','b'],['a'],['b','c'],['c','d'],['b'], ['a','d']] # do flat list for auto index flat_list = list(chain(*list1)) # remove duplicates flat_list = list(OrderedDict.fromkeys(flat_list)) mapping = {x:flat_list.index(x)+1 for x in set(flat_list)}  [{e: mapping[e] for e in li} for li in list1] 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: