'Python return dictionary with corresponding letters
The function should return the words if they match with a letter in the dictionary.
Example:
print(returnLetter(list1))
{'I': ['I'], 'say': ['say', 'what', 'mean', 'and'], 'what': ['say', 'what', 'mean', 'and'], 'mean': ['say', 'what', 'mean', 'and'],
'and': ['say', 'what', 'mean', 'and']}
The function I currently have only returns it if it matches with the first letter, and I have been messing with the indexing and cannot figure it out.
def returnLetter(inpt):
result = {}
for word in inpt:
char = word[0]
if char in result:
result[char].append(word)
else:
result[char] = [word]
return result
This will return every word with the first letter in the list, but it should be going through every letter instead of just the first.
Solution 1:[1]
Edit: Here's the edited code as required:
def return_letter(l: list):
result = dict()
# Creating starting dictionary
for word in l:
if word not in result.keys():
result[word] = []
# Iterating over keys and words in the list and adding all matching words
for word, v in result.items():
for letter in word:
for w in result.keys():
if w not in v and letter in w:
v.append(w)
return result
text = "and I say what you mean"
print(return_letter(text.split(' ')))
output:
{'and': ['and', 'say', 'what', 'mean'], 'I': ['I'], 'say': ['say', 'and', 'what', 'mean', 'you'], 'what': ['what', 'and', 'say', 'mean'], 'you': ['say', 'you'], 'mean': ['mean', 'and', 'say', 'what']}
Hopefully, my code is clear enough, if something is unclear be sure to leave a comment.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
