Hi everyone,

I am going through a self-paced class for Python beginners and have ran into a dictionary problem that I can't figure out. I'm creating a set of words from user input. Then send those words to a dictionary that adds a key for when the word is first used. My problem is the dictionary clears after every input although it is suppose to maintain the dictionary items. Could someone please point out where I am off?

while True:
    text = input("Enter text: ")
    
    for punc in ",?;.":
        text = text.replace(punc, "")
        
    words = {}
    seen = set()

    for word in text.lower().split():
        size_seen = len(seen)
        seen.add(word)
        if len(seen) > size_seen:
            words[word] = len(seen)

    if text == "":
        break

    for word in words:
        print(word, ":", words[word])

print("Finished")

Thanks for the help in advance

is it because you put words = {} inside the While clause? this way, it get initialized to an empty dic in every While cycle.

is it because you put words = {} inside the While clause? this way, it get initialized to an empty dic in every While cycle.

Thank you so much! Worked like a charm.

I do not understand what you are doing this seen set stuff.

By testing the code I understood you wanted to record the number of each word as it occurs. I would do for example like this instead of the length stuff:

from __future__ import print_function
try:
    input = raw_input
except:
    pass
    
seen = dict()
current = 1
text = 'Here goes the text'

while text != "":
    text = input("Enter text: ")
    
    for punc in ",?;.":
        text = text.replace(punc, "")
    for word in text.lower().split():
        if word not in seen:
            seen[word] = current
            current += 1

    for word, place in sorted(seen.items()):
        print(place, ":", word)

print("Finished")
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.