Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Dictionary question
#1
This will make my look like a nooby - I am, but I am going nuts - help!
The following snippet works exactly as I would expect. It iterates through a list and each string
in that list becomes a key in what started as an empty dictionary.

def main():
    my_dictionary = {}
    alist = ["x", "y", "z"]
    for s in alist:
        my_dictionary[s] = 1
    print(my_dictionary)
    
main()
Now for the code that does not work - why? See line #24

# Characters to delete from our words
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''

def remove_puncts(s):
    punct_free = ""
    for char in s:
        if char not in punctuations:
            punct_free += char.lower()
    return (punct_free)


def main():
 
    
    word_frequency = {}  # Create an empty dictionary
    line_cnt = 0

    with open("counterTXT.txt") as f:   # Open a file
        for i in f:                     # Read each line
            line_cnt += 1
            my_line = remove_puncts(i)     # Remove punctuation characters
            line_words = my_line.split()   # Convert string to list of words
            for s in line_words:           # For each word, increment dict counter
                word_frequency[s] += 1     #  indexing word_frequency causes failure
  
    for k, v in word_frequency.items():
        print(k, v)


main()
This is going to be embarrassing, but I can take it. :-)
Reply


Messages In This Thread
Dictionary question - by DrZ - Jul-29-2020, 08:43 PM
RE: Dictionary question - by ndc85430 - Jul-29-2020, 08:45 PM
RE: Dictionary question - by DrZ - Jul-29-2020, 08:53 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  General Programming Question with Dictionary giddyhead 12 2,929 Jan-10-2022, 10:12 AM
Last Post: Pedroski55

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020