-1

Below code works fine for array:

g = ['hello how are you', 'how are you guys','what is your name']
s = ['how','guys']
MIN_MATCH_SCORE = 38
guessed_word = [word for word in g if fuzz.token_set_ratio(s, word) 
                                               >=  MIN_MATCH_SCORE]

output: 'hello how are you' 'how are you guys'

how to achieve above with dictionary ?

p = [{1: 'hey guys'},
    {1: 'how are you all'},
    {1: 'hello guys, how are you doing'}]

expected output:

{1: 'hello how are you'}, {1: 'how are you guys'}

Hope i get some response.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Titan
  • 244
  • 1
  • 4
  • 18
  • 1
    This is a pretty basic traversal logic. Have you even tried this before asking out? All you need to traverse is element of the list p, which are dict, so get their values. – em_bis_me Jul 12 '21 at 10:15
  • can you please tell with working example ? – Titan Jul 12 '21 at 10:21
  • please see my expected output. – Titan Jul 12 '21 at 10:25
  • There is an error in your list comprehension for `guess_word`. If should be word not word[1] (i.e. word[1] is just a single letter). With the current code guessed_word is []. – DarrylG Jul 12 '21 at 10:55
  • now it works please check, just removed[0] from word – Titan Jul 12 '21 at 11:08
  • Why does p have different string comments than g (e.g. 'hello how are you' in g vs. 'hey guys' in p)? – DarrylG Jul 12 '21 at 11:20

3 Answers3

2
from fuzzywuzzy import fuzz

p = [{1: 'hey guys'},
    {1: 'how are you all'},
    {1: 'what is your name'}]

s = ['how','guys']

MIN_MATCH_SCORE = 38
guessed_word= []

for i in p:
    for key,value in i.items():  #dict.items used to access the (key-value) pair of dictionary
        if(fuzz.token_set_ratio(s, value) >= MIN_MATCH_SCORE): #check the condition for each value , if it's satisfied create a dictionary & append it to result list
            dict={}
            dict[key]=value
            guessed_word.append(dict)

print(guessed_word) 

The output will be :

[{1: 'hey guys'}, {1: 'how are you all'}]

Nilaya
  • 148
  • 8
1

Your list comprehension can be converted to the following to use dictionaries.

guessed_word = [d for d in p if fuzz.token_set_ratio(s, list(d.values())[0]) >= 
                                                       MIN_MATCH_SCORE]

Explanation:

 d iterates over the dictionaries
 list(d.values())[0] is the string portion of the dictionary i.e. 'hey guys', etc.
DarrylG
  • 16,732
  • 2
  • 17
  • 23
0

#This one also works. #g in p are in my usecase.

guessed_word= []
for p in g:
    for k,l in p.items():
        l = [l]
        #d = [fuzz.token_set_ratio(s,l) >= MIN_MATCH_SCORE]
        d= [word for word in l if fuzz.token_set_ratio(s, word) >= 
          MIN_MATCH_SCORE]
        guessed_word.append({k:d})
Titan
  • 244
  • 1
  • 4
  • 18