[Solved] How to create a dict in python from two List of Lists [closed]


You could do it as follows –

lists1 = [ ['a','b'], ['c','d'], ['e','f'] ]
lists2 = [ [1,2], [3,4], [5,6] ]
 
dictionary = {}

# Loops through inner lists of both lists at same time - l1 for lists1 and l2 for lists2 
for l1,l2 in zip(lists1,lists2):
    # Loops through the elements of inner list of lists1 & lists2, that is l1 and l2
    for elem1,elem2 in zip(l1,l2):
        dictionary[elem1] = elem2   # Simply assign element from list1 as keys to corresponding elements from lists2
print(dictionary)   

 

Output :

{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}

A more pythonic way of doing it would be as follows –

lists1 = [ ['a','b'], ['c','d'], ['e','f'] ]
lists2 = [ [1,2], [3,4], [5,6] ]

dictionary = {k:v for l1,l2 in zip(lists1,lists2) for k,v in zip(l1,l2)}
print(dictionary)   

Output :

{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}

2

solved How to create a dict in python from two List of Lists [closed]