title: Inverted index given a list of document tokens using python?
body: <p>I'm a newbie to python. I need to create an inverted index function given a list of document tokens. The index maps each unique word to a list of document ids, sorted in increasing order.</p>
  
  <p>My code:</p>
  
  <pre><code>def create_index(tokens):
      inverted_index = {}
      wordCount = {}
      for k, v in tokens.items():
          for word in v.lower().split():
              wordCount[word] = wordCount.get(word,0)+1
              if inverted_index.get(word,False):
                  if k not in inverted_index[word]:
                      inverted_index[word].append(k)
              else:
                  inverted_index[word] = [k]
      return inverted_index, wordCount
  </code></pre>
  
  <p>Note: This works fine when the input argument is of the form <code>{1:"Madam I am Adam",2: "I have never been afraid of him"}
  </code></p>
  
  <p>output that i get for the above example:</p>
  
  <pre><code>{'madam': [1], 'afraid': [2], 'i': [1, 2], 'of': [2], 'never': [2], 'am': [1], 'been': [2], 'adam': [1], 'have': [2], 'him': [2]}
  </code></pre>
  
  <p>As per my code K,v correspond to Key and value of the list </p>
  
  <p>Desired output when we call the create_index function with an argument:</p>
  
  <pre><code>index = create_index([['a', 'b'], ['a', 'c']])
  &gt;&gt;&gt; sorted(index.keys())
  ['a', 'b', 'c']
  &gt;&gt;&gt; index['a']
  [0, 1]
  index['b']
  [0]
  index['c']
  [1]
  </code></pre>