1

I have a list & a dictionary.

l = ['one', 'two', 'three', 'four']
d = {'aw.one' : '#aw.one', 'aw.two' : '#aw.two'}

Now, I have a string :

s = "this is one sentence"

I want to check if any items in list l is present in string or not. If yes, then I want to get the value from dictionary whose key contains that item from list.

for example, in given example
- 'one' from string is present in list l - then I need #aw.one to be printed.

If my string is :

s = "this is two balls"

it should print

#aw.two.

How can I do that?

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
sam
  • 18,509
  • 24
  • 83
  • 116

5 Answers5

1

The straight forward way is to iterate the list and check if the word is in s and then iterate the dictionary keys to check if any of them has the word in it, like this

for item in l:
    if item in s:
        for key in d:
            if item in key:
                print d[key]

Instead of writing the same in multiple lines, we can even write that like this

print ", ".join(", ".join(d[k] for k in d if i in k) for i in l if i in s)
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
1

Maybe the best approach is build a dict which keys are value parts, so to find if it exists only cost O(1)

>>> import re
>>> l = ['one', 'two', 'three', 'four']
>>> d = {'aw.one' : '#aw.one', 'aw.two' : '#aw.two'}
>>> s = "this is two balls"
>>> d_reversed = {
...     v_part:k
...     for k,v in d.iteritems()
...     for v_part in re.findall(r"[\w']+", v) #for all words from every value
...     
... }
>>> for w in s.split():
...     if w in d_reversed:
...         print d_reversed[w], d[d_reversed[w]] #print the key from the main dict, and its value
...         break
... 
aw.two #aw.two
xecgr
  • 5,095
  • 3
  • 19
  • 28
1

You can achieve the same thing with couple list comprehensions and a filter lambda:

matching_words = [ word for word in l if word in s ]
matching_values = [ value for key, value in d.items() if list(filter(lambda x: x in key, matching_words)) ]
for value in matching_values:
    print(value)
svvitale
  • 111
  • 1
  • 8
0

If your key prefix is always the same:

>>> l = ['one', 'two', 'three', 'four']
>>> d = {'aw.one' : '#aw.one', 'aw.two' : '#aw.two'}
>>> s = "this is one sentence"
>>> print(''.join(d.get('aw.{}'.format(w)) for w in l if w in s))
#aw.one
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
0

Using set and dictionary:

print [d['aw.'+i] for i in (set(s.split()) & set(l)) if 'aw.'+i in d]
venpa
  • 4,268
  • 21
  • 23