Angel Angel - 18 days ago 9
Python Question

Word position function using dictionary

Write a function that returns a dictionary that for each word found in the makes into a list of its positions

Answer

Here you go. You can use enumerate to grab the position of each word after you split the input phrase. Then just append to the list of a dictionary.

def wordposition(phrase):
    words = phrase.split(' ')
    out = {}
    for i,word in enumerate(words):
        if word in out:
            out[word].append(i)
        else:
            out[word] = [i]
    return out

>>> wordposition("he thought a thought that he thought he’d never think")
# {'a': [2],
#  'he': [0, 5],
#  'he’d': [7],
#  'never': [8],
#  'that': [4],
#  'think': [9],
#  'thought': [1, 3, 6]}
Comments