I have a string that I'm turning into a list. I then count the words in that list and I'm trying to use that number (length) as a counter so that I can add each word to a dictionary with a number as their key. It seems to enumerate correctly but it's only reading the last entry on the list instead of word for word.
Any idea why it's only reading the last entry on the list i.e. 'you?'?
mystring = "Hello mate how are you?"
mylist = mystring.split()
lengh = len(mylist)
class my_dictionary(dict):
# __init__ function
def __init__(self):
self = dict()
# Function to add key:value
def add(self, key, value):
self[key] = value
# Main Function
dict_obj = my_dictionary()
for x in range(lengh):
for line in mylist:
for word in line.split():
dict_obj.add(x, line)
print(dict_obj)
output is:
{0: 'you?', 1: 'you?', 2: 'you?', 3: 'you?', 4: 'you?'}
Output should be:
{0: 'Hello?', 1: 'mate?', 2: 'how', 3: 'are', 4: 'you?'}