How to call a dictionary from my first function in my second function in Python
<p>I am pretty new to Python and to help new learn, I am building a program, which I want broken down into 2 steps:</p>

<p>Step 1) Count the number of a particular words in a text file, store that in a dictionary where the key, value pairs are {word, count}</p>

<p>Step 2) Order the dictionary from (1) in descending order, to show the top 100 words</p>

<p>Step 1 works fine but in attempting step 2, I am struggling to call the dictionary from the first function. I create a new variable 'tallies' but this is a tuple and shows only the first entry in the dictionary.</p>

<p>How do I call the full dictionary to my 2nd function?</p>

<p>Thanks.</p>

<pre><code>filename = 'nameoffile.txt'

def tally():
  file = open(filename,'r')
  wordcount={}
  for word in file.read().split():
    if word not in wordcount:
      wordcount[word] = 1
    else:
      wordcount[word] += 1
  for k,v in wordcount.items():
    return k,v

def Count():
  tallies = tally()
  print tallies

Count()
</code></pre>

<p>your tally function is returning the first item it sees; <code>return</code> can only return once, but you're calling it in a loop.  try returning the whole wordcount dict:</p>

<pre><code>filename = 'nameoffile.txt'

def tally():
  file = open(filename,'r')
  wordcount={}
  for word in file.read().split():
    if word not in wordcount:
      wordcount[word] = 1
    else:
      wordcount[word] += 1
  return wordcount

def Count():
  tallies = tally()
  sorted_tallies = sorted(tallies.items(), key=operator.itemgetter(1))
  print sorted_tallies[:100]

Count()
</code></pre>

<p>in python a <code>dict</code> is by nature unordered, so to order it you need to sort its tuples into a list.  the <code>sorted</code> code does this (<a href="http://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value">see this reference</a>).</p>

<p>good luck!</p>

python dictionary