Reputation: 5
The question is to create a function that reads a string and print a dictionary listing the positions for each UNIQUE word. The key is the word and the value is a list of its positions in the string.
Here would be an example string:
One fish two fish red fish blue fish
The correct output would be:
{'two': [2], 'one': [0], 'red': [4], 'fish': [1, 3, 5, 7], 'blue': [6]}
Here is my output:
{'blue': [6], 'two': [2], 'red': [4], 'fish': [1], 'One': [0]}
As you notice, the word 'fish' is repeated multiple times in this string. It is not just in position 1. What code do I need to add to print out the multiple positions of any word?
Here is my code:
def wordPositions(s):
d = {}
words = s.split()
for word in words:
lst = []
lst.append(words.index(word))
d[word] = lst
return d
print(wordPositions('One fish two fish red fish blue fish'))
Upvotes: 0
Views: 84
Reputation: 61014
from collections import defaultdict
s = 'One fish two fish red fish blue fish'
d = defaultdict(list)
for i, word in enumerate(s.split()):
d[word.lower()].append(i)
Use collections.defaultdict
and enumerate
. d.items()
is then
dict_items([('one', [0]), ('blue', [6]), ('two', [2]), ('red', [4]), ('fish', [1, 3, 5, 7])])
Upvotes: 1
Reputation: 21643
And yet another answer ...
>>> words='One fish two fish red fish blue fish'.split()
>>> counts={}
>>> for word in set(words):
... counts[word]=[_ for _ in range(len(words)) if words[_]==word]
...
>>> counts
{'blue': [6], 'two': [2], 'fish': [1, 3, 5, 7], 'red': [4], 'One': [0]}
Upvotes: 0
Reputation: 19806
Try the following code using enumerate()
:
s = 'One fish two fish red fish blue fish'
res = {}
for i, v in enumerate(s.split(' ')):
if v in res:
res[v].append(i)
else:
res[v] = [i]
Output:
>>> res
{'blue': [6], 'fish': [1, 3, 5, 7], 'two': [2], 'red': [4], 'One': [0]}
Upvotes: 0