Compare list of lists with a dictionary and get output as list of list of tuples

73 Views Asked by At

I have a list of list of strings and a dictionary:

docsp = [['how', 'can', 'I', 'change', 'this', 'car'], ['I', 'can', 'delete', 'this', 'module']]

ent = {'change' : 'action', 'car' : 'item', 'delete' : 'action'}

I want to compare the dictionary with the list of lists and tag the list elements with dictionary key value pairs to a new list of tuples like below.

newlist = [[('how', 'O'), ('can', 'O'), ('I', 'O'), ('change', 'action'), ('this', 'O'), ('car', 'item')], [('I', 'O'), ('can', 'O'), ('delete', 'action'), ('this', 'O'), ('module', 'O')]]

I tried the following code:

n = []
for k,v in ent.items():
    for i in docsp:
        for j in i:
            if j==k:
                n.append((j,v))
            n.append((j, 'O'))
n

and getting the below output:

[('how', 'O'),
 ('can', 'O'),
 ('I', 'O'),
 ('change', 'action'),
 ('change', 'O'),
 ('this', 'O'),
 ('car', 'O'),
 ('I', 'O'),
 ('can', 'O'),
 ('delete', 'O'),
 ('this', 'O'),
 ('module', 'O'),
 ('how', 'O'),
 ('can', 'O'),
 ('I', 'O'),
 ('change', 'O'),
 ('this', 'O'),
 ('car', 'item'),
 ('car', 'O'),
 ('I', 'O'),
 ('can', 'O'),
 ('delete', 'O'),
 ('this', 'O'),
 ('module', 'O'),
 ('how', 'O'),
 ('can', 'O'),
 ('I', 'O'),
 ('change', 'O'),
 ('this', 'O'),
 ('car', 'O'),
 ('I', 'O'),
 ('can', 'O'),
 ('delete', 'action'),
 ('delete', 'O'),
 ('this', 'O'),
 ('module', 'O')]

I went through this link , but unable to modify it to get my expected output.

1

There are 1 best solutions below

2
On BEST ANSWER

This is one solution utilising list comprehension:

docsp = [['how', 'can', 'I', 'change', 'this', 'car'], ['I', 'can', 'delete', 'this', 'module']]

ent = {'change' : 'action', 'car' : 'item', 'delete' : 'action'}

result = [[(docsp[i][j], ent.get(docsp[i][j], 'O')) for j in range(len(docsp[i]))] \
                                                    for i in range(len(docsp))]

# [[('how', 'O'),
#   ('can', 'O'),
#   ('I', 'O'),
#   ('change', 'action'),
#   ('this', 'O'),
#   ('car', 'item')],
#  [('I', 'O'),
#   ('can', 'O'),
#   ('delete', 'action'),
#   ('this', 'O'),
#   ('module', 'O')]]