1

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)
Lucas Amos
  • 1,117
  • 4
  • 15
  • 36

1 Answers1

3

__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()

Community
  • 1
  • 1
DilithiumMatrix
  • 17,795
  • 22
  • 77
  • 119
  • I'd like to add (for OP's understanding) that you can't have a Java constructor outside of a class either. – Alex Hall Oct 18 '15 at 20:37