codeforfun
codeforfun

Reputation: 187

how to evaluate if dictionary key is in a string

I have a dictionary dict and a string text. I need to evaluate if the keys of the dictionary appear in the string and to print them as many times they appear. I have tried the code below but the error is: must be str, not dict_keys

for word in text.split():
    if text.find(dict.keys()) != -1:
        print(word/n)

Sample data:

dictionary:

{'abandon': -2, 'abandoned': -2, 'abandons': -2, 'abducted': -2, 'abduction': -2}

text:

"Brenamae_ I WHALE SLAP YOUR FIN AND TELL YOU ONE LAST TIME: GO AWHALE Metin Şentürk Twitterda @metinsenturk MUHTEŞEM ÜÇLÜ; SEN, BEN, MÜZİK RT @byunghns: 😭 I LOVE #틴탑 SO MUCH #쉽지않아 IS GOING TO BE SO GOOD 😭 que hdp maicon lo que le hizo a david luiz jajajajajajajajajajaj,igual se jodio la carrera ドラ"

Upvotes: 1

Views: 1190

Answers (3)

Laurent H.
Laurent H.

Reputation: 6526

As already written by @MarcoBonelli, your error is easily explained:

As Python warns you, dict.keys() is not a string, so you cannot call .find(dict.keys()), which wants a string as argument.

My suggestion is to use a comprehension to loop over the keys of the dictionary, and to use the str.count() method to get the number of times they appear in the string. With the following example, you obtain a list of sublists with your needed information:

d = {'d':2, 'e':-1, 'z':0}
t = 'mey tayeelor ddis erich'

r = [[k]*t.count(k) for k in d if k in t]
print(r) # [['d','d'], ['e','e','e','e,]]

Upvotes: 1

Marco Bonelli
Marco Bonelli

Reputation: 69522

As Python warns you, dict.keys() is not a string, so you cannot call .find(dict.keys()), which wants a string as argument.

What you want is to iterate over each key and check each of them separately. What you're currently doing does not make much sense.

The correct code for what you want to do:

I need to evaluate if the keys of the dictionary appear in the string and to print them as many times they appear.

Is the following:

for k in dict.keys():
    if k in text:
        for i in range(text.count(k)):
            print(k)

This could be optimized to only scan text once, but I'll leave that to you.

Also, I would very much suggest you to not call your dictionary dict as that is the name of the default dictionary class. Use a different name.

Upvotes: 2

Vicrobot
Vicrobot

Reputation: 3988

str.find takes input as string, thus error.

You can try making other function like this:

def isin(string, keys):
    return any([str(i) in string for i in keys])

Upvotes: 0

Related Questions