Pnelson
Pnelson

Reputation: 57

Search a word in a dictionary

I want to input a letter and i want to return all the words that contain that letter. For example:

String: "I saw a frog in my garden"
input: g
output: frog, garden

How could make this in Python?

Upvotes: 0

Views: 312

Answers (3)

bobbruno
bobbruno

Reputation: 94

I am assuming that you have split the string as a list of words and created a dictionary using those words as keys. given that, the following function takes a dictionary and a character and returns a list of keys on that dictionary which have that character:

def keys_have_char(dict, char):
    return [key for key in dict.keys() if char in key]

Notice that I haven't added any checks, so this assumes that dict is indeed a dictionary and will work not only with single chars, but with any substrings as well.

Upvotes: 0

user3286261
user3286261

Reputation: 501

It is quite useful to know which letter the list represents:

contains = {}
contains[letter] = [w for w in String.split() if letter in w]

Upvotes: 0

anon582847382
anon582847382

Reputation: 20351

I don't know what you are talking about regarding dictionaries (you may misunderstand them)- but I would just split up the word and then check if the letter was in each one, within a list comprehension.

>>> String = "I saw a frog in my garden"
>>> letter = 'g'
>>> [w for w in String.split() if letter in w]
['frog', 'garden']

That seems to be what you want.

Upvotes: 5

Related Questions