Unable to call a function within a function in python

Question:

Build a “mimic” dict that maps each word that appears in the file
to a list of all the words that immediately follow that word in the file.
The list of words can be be in any order and should include
duplicates. So for example the key “and” might have the list
[“then”, “best”, “then”, “after”, …] listing
all the words which came after “and” in the text.
We’ll say that the empty string is what comes before
the first word in the file.

With the mimic dict, it’s fairly easy to emit random
text that mimics the original. Print a word, then look
up what words might come next and pick one at random as
the next work.
Use the empty string as the first word to prime things.
If we ever get stuck with a word that is not in the dict,
go back to the empty string to keep things moving.

Defining first function:

def mimic_dict(filename):
    with open (filename, 'r+') as x:
        x = x.read()
        x = x.split()
        dic = {}
        for i in range(len(x)-1):  
            if x[i] not in doc:    
                dic[x[i]] = [x[i+1]]   
            else:                      
                dic[x[i]].append(x[i+1])

    print(dic)


mimic_dict('small.txt')

OUTPUT:

{'we': ['are', 'should', 'are', 'need', 'are', 'used'], 'are': ['not', 'not', 'not'], 'not': ['what', 'what', 'what'], 'what': ['we', 'we', 'we'], 'should': ['be'], 'be': ['we', 'but', 'football'], 'need': ['to'], 'to': ['be', 'be'], 'but': ['at'], 'at': ['least'], 'least': ['we'], 'used': ['to']}

Defining second function with first fucntion called within it

import random

def print_mimic(x): 
    l = []
    for i in range(5):
        word = random.choice(list(x.items()))
        l.append(word)

    print(l)      

print_mimic(mimic_dict)

AttributeError                            Traceback (most recent call last)
<ipython-input-40-c1db7ba9ddae> in <module>
      8 
      9     print(l)
---> 10 print_mimic(d)

<ipython-input-40-c1db7ba9ddae> in print_mimic(x)
      4     l = []
      5     for i in range(2):
----> 6         word = random.choice(list(x.items()))
      7         l.append(word)
      8 

AttributeError: 'NoneType' object has no attribute 'items'

Please advise why is the second function failing to call the first function? Or why am I getting this error?

Asked By: Hasham Beyg

||

Answers:

I have to make some assumptions because you left out the only important part.

If you attempt to make your example simpler you will see it is likely because you are assigning to a function that doesn’t return anything, only prints.

def foo():
   x = amazing_calculation()
   print x

def bar(x):
   print x

>>> y = foo()
amazing
>>> bar(y)   # foo doesn't return anything, so 'y' is None
None
Answered By: Cireo