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 issue is that you returned <code>k,v</code> after the first iteration meaning you only ever grabbed the first item. The following code fixes this. I also added the reversal function.</p>

<pre><code>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 tuple(reversed(sorted(((k, v) for k, v in wordcount.items()),key=lambda x: x[1])))

def Count():
    tallies = tally()
    print tallies
</code></pre>

python dictionary