user7831701
user7831701

Reputation:

Python - mapping list of lists to dictionary

I want to make a correlation between a list of lists and a dictionay of lists. On one hand, I have the following list:

list_1=[['new','address'],['hello'],['I','am','John']]

and on the other hand I have a dictionary of lists:

dict={'new':[1,3,4], 'address':[0,1,2], 'hello':[7,8,9], 'I':[1,1,1], 'John':[1,3,4]}

What I want to get is a new list of lists (of lists) like this:

list_2=[[[1,3,4],[0,1,2]],[[7,8,9]],[[1,1,1],[0,0,0],[1,3,4]]]

This means that every word from list_1 was mapped to each value in the dictionary dict and what is more, notice that 'am' from list_1 that was not found in dict took values [0,0,0].

Thanx in advance for the help.

Upvotes: 1

Views: 74

Answers (2)

Rafael Quintela
Rafael Quintela

Reputation: 2228

list_1=[['new','address'],['hello'],['I','am','John']]
dict={'new':[1,3,4], 'address':[0,1,2], 'hello':[7,8,9], 'I':[1,1,1], 'John':[1,3,4]}
list_2=[[dict[x] for x in l if x in dict] for l in list_1]

if you want a list even if the key doesn't exists in dict

list_2=[[dict.get(x, []) for x in l] for l in list_1]

Upvotes: 0

Jean-François Fabre
Jean-François Fabre

Reputation: 140307

just rebuild the list of lists using dictionary queries using dict.get, and a default value in case the key isn't found:

list_1=[['new','address'],['hello'],['I','am','John']]

d={'new':[1,3,4], 'address':[0,1,2], 'hello':[7,8,9], 'I':[1,1,1], 'John':[1,3,4]}

list_2=[[d.get(k,[0,0,0]) for k in sl] for sl in list_1]

print(list_2)

result:

[[[1, 3, 4], [0, 1, 2]], [[7, 8, 9]], [[1, 1, 1], [0, 0, 0], [1, 3, 4]]]

Upvotes: 1

Related Questions