Python dictionary: Changing one value for a dictionary key in a loop changes every value for every key instead

I have a list of characters. I would like to pull the punctuation out of the list and make each type of punctuation a key in a dictionary (so a key for ".", a key for "!", etc.) Then, I would like to count the number of times each punctuation character occurs in another list and make that count the value for the corresponding key. Problem is, every value in my dictionary changes instead of just the one key.

The output should look like this because there are 2 "." and 4 "!" in the ‘punctuationList’

{‘.’: [2], ‘,’: [0], ‘!’: [4], ‘?’: [0]}

But instead looks like this because the "!" appears 4 times

{‘.’: [4], ‘,’: [4], ‘!’: [4], ‘?’: [4]}

# Create a list of characters that we will eventually count
charList = [".","!",".","!","!","!","p","p","p","p","p"]

# Create a list of the punctuation we want a count of
punctuationList = [".",",","!","?"]

# Group each type of punctuation and count the number of times it occurs

dic = dict.fromkeys(punctuationList,[0]) # Turn punctuationList into a dictionary with each punctuation type as a key with a value that is 
                                         # the count of each time the key appears in newList

print (dic)

# Count each punctuation in the dictionary

for theKey in dic: # iterate through each key (each punctuation type)
    counter = 0  # Set the counter at 0
    for theChar in charList: # If the key matches the character in the list, then add 1 to the counter
        if theKey == theChar:
            counter = counter + 1
            dic[theKey][0] = counter # Then change the value of that key to the number of times 
                                                   # that character shows up in the list

print (dic)

>Solution :

dict.fromkeys shares the same value for each key.

You’ll want

dic = {key: [0] for key in punctuationList}

instead to initialize a separate list for each key. (As an aside, there really is no need to wrap the number in a list.)

That said, your code could be implemented using the built-in collections.Counter in just

from collections import Counter
dic = dict(Counter(ch for ch in charList if ch in punctuationList))

Leave a Reply