I am a Python newbie so I apologise in advance for what is probably a stupid question. I have written a function that maps each letter of the alphabet to its corresponding prime number. That function works fine.
The problem I am having is that I want to create a dict and then set the 'dictionary' variable to the result of the 'populateprimelist' function which returns a dict. I am trying to do this in ' init ' function which I understand to be the equivalent of a Java constructor. However when I print out the 'dictionary' variable in the main method it is empty.
dictionary = dict()
def __init__(self):
dictionary = self.populateprimelist()
def populateprimelist():
primelist = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101]
alphabet = "abcdefghijklmnopqrstuvwxyz"
tempdict = dict()
for index in range(len(alphabet)):
tempdict[(alphabet[index])] = (primelist[index])
return tempdict
if __name__ == '__main__':
print(dictionary)
__init__
is used in a class
--- and you haven't defined a class here. Check out this answer .
Presumably, you either want to put your __init__
and populateprimelist
functions into a class
. Or, you don't actually need to define a class here, you can just create your 'prime-list' dictionary with a normal function call:
if __name__ == '__main__':
dictionary = populateprimelist()
print(dictionary)
You don't need self
, because there's no custom class being used.
You also don't need that first dictionary initialization dictionary = dict()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.