Angel Angel - 1 year ago 166
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 Source

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] = [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]}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download