Hemil Patel
Hemil Patel

Reputation: 23

How to make a dictionary from two nested list?

I have two nested lists:

list1 = [['s0'], ['s1'], ['s2']]
list2 = [['hello','world','the'],['as','per','the'],['assets','order']]

and I want to make a dictionary from these lists with keys from list1 and values from list2:

d = {s0:['hello','world','the'],s1:['as','per','the'],s2:['assets','order']}

The output should look like this:

d = {s0:['hello','world','the'],s1:['as','per','the'],s2:['assets','order']}

The following code works if list1 is a normal (non-nested) list. But it doesn't work when list1 is a nested list.

dict(zip(list1, list2))

Upvotes: 2

Views: 281

Answers (4)

Stefan
Stefan

Reputation: 352

It's a strange way to store matching information in the first place, but I would combine them like this:

list1 = [['s0'], ['s1'], ['s2']]
list2 = [['hello','world','the'],['as','per','the'],['assets','order']]

assert(len(list1) == len(list2))
output_dict = dict()
for index in range(len(list1)):
    output_dict[list1[index][0] = list2[index]

result:

{'s0': ['hello', 'world', 'the'], 's1': ['as', 'per', 'the'], 's2': ['assets', 'order']}

I am assuming that the variables s0, s1 and s2 are meant to be strings like in the first list.

Upvotes: 0

Kaies LAMIRI
Kaies LAMIRI

Reputation: 199

Another answer could be :

list1 = [['s0'], ['s1'], ['s2']]
list2 = [['hello','world','the'],['as','per','the'],['assets','order']]
output_dict = {element1[0]: element2 for element1, element2 in zip(list1, list2)}

An similar way of this dict-comprehension :

output_dict = {element1: element2 for [element1], element2 in zip(list1, list2)}

Output :

{'s0': ['hello', 'world', 'the'],
 's1': ['as', 'per', 'the'],
 's2': ['assets', 'order']}

Upvotes: 2

yatu
yatu

Reputation: 88305

The problem here is that lists are not hashable, so one thing you can do is to flatten your list with itertools.chain and then build the dictionary with strings (which are immutable) as keys following you're current approach (read here for a more detailed explanation on this topic):

from itertools import chain

dict(zip(chain.from_iterable(list1),list2))

{'s0': ['hello', 'world', 'the'],
 's1': ['as', 'per', 'the'],
 's2': ['assets', 'order']}

Upvotes: 6

politinsa
politinsa

Reputation: 3720

If you want to do it manually (to understand algorithm for exemple), here is a way to do so:

list1 = [['s0'], ['s1'], ['s2']]
list2 = [['hello','world','the'],['as','per','the'],['assets','order']]

if len(list1) != len(list2):
    exit(-1)

res = {}
for index, content in enumerate(list1):
    res[content[0]] = list2[index]

print(res)

Upvotes: 2

Related Questions