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
#2
Yes, because the key is not in the dictionary. Line 24 in the second piece of code is not the same as line 5 in the first - the latter associates the value with the key, but the former tries to read the value associated with the key and then tries to increment it. Since the key isn't there, a KeyError is raised. You either need to handle the case of the key not being there, or use defaultdict in the collections module.
Reply
#3
A big duh to me!

I am aware of the collections module and I have made it work with that. I just wanted to try it starting with a vanilla dictionary.
Thanks so much for your quick and useful reply!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  General Programming Question with Dictionary giddyhead 12 2,750 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