Reputation: 1
Below I have a list and dict with the values as below. The dict has keys associated with list values.
What I wanted was to search strings in the list with values of the list in the dictionary and with each match capture the corresponding key value and create a new list with the key values for each match as above listed.
list = ['man', 'men', 'boy', 'buoy', 'cat','caat']
dict={'man':['man', 'men', 'mun'], 'boy':['boy','buoy','bay'], 'cat':['cat','caat','cut']}
Expected output for above case is: Outputlist=['man','man','boy','boy','cat','cat']
When I tried the same I am getting only one item to match as below.
lis = ['man', 'men', 'boy', 'buoy', 'cat','caat']
dic={'man':['man', 'men', 'mun'], 'boy':['boy','buoy','bay'], 'cat':['cat','caat','cut']}
for key,value in dic.items():
if value in lis:
output.append(key)
print(output)
Upvotes: 0
Views: 1574
Reputation: 320
I think you did it the wrong way. First, you wan to go across the lis and after find the corresponding key :
output = []
lis = ['man', 'men', 'boy', 'buoy', 'cat','caat']
dic={'man':['man', 'men', 'mun'], 'boy':['boy','buoy','bay'], 'cat':['cat','caat','cut']}
for l in lis:
for key, value in dic.items():
if l in value:
output.append(key)
print(output)
As the others mention, you can use list comprehension to do it directly:
output = [next(k for k,v in dict if l in v) for l in list]
Upvotes: 0
Reputation: 27201
The first thing to note is that to achieve the same length input and output lists, you should be looping over the list, not the dictionary.
ys = [k for x in xs for k, v in d.items() if x in v]
Another way is to construct a reverse mapping. This should make things asymptotically faster:
lookup = {x: k for k, v in d.items() for x in v}
>>> lookup
{
'bay': 'boy',
'boy': 'boy',
'buoy': 'boy',
'caat': 'cat',
'cat': 'cat',
'cut': 'cat',
'man': 'man',
'men': 'man',
'mun': 'man',
}
Then, simply:
ys = [lookup[x] for x in xs]
Upvotes: 1
Reputation: 1442
you can use a nested list comprehension
. Notice that you should not use list
and dict
as variables:
x = [key for key, value in dict_.items() for x in list_ if x in value]
print(x) # ['man', 'man', 'boy', 'boy', 'cat', 'cat']
Upvotes: 5