I want to write a program in which as an input I take a list consisted of words which can contain punctuation marks. I built a dictionary where keys are elements of a given list and values are empty lists. My goal is to add to these lists (inside the this dictionary) the indexes of those chars from the words which are punctuation marks. The program works partially - the problem is, that it adds the proper index to the previous list, i. e. to the list for the previous key, not for the current one. If you analyze the code, you will see what I mean:
list1 = ['!,', 'Hey!']
dict_words = dict.fromkeys(list1, [])
print(list1)
print(dict_words)
print()
for word in list1:
counter_punc = 0
print('"word": ', word, ' dict_words["word"]: ', dict_words[word])
if word.isalpha():
print("alpha word: ", word)
else:
print("non-alpha word: ", word)
for letter in word:
if letter.isalpha():
print("alpha letter: ", letter) #, " non-alpha word: ", word)
else:
counter_punc += 1
dict_words[word].append(word.index(letter))
print("letter: ", letter, " index: ", word.index(letter))
print('"word": ', word, ' dict_words["word"]: ', dict_words[word])
# dict_words[word].append()
print("word: ", word, " counter_punc: ", counter_punc)
print()
Iterating through the items of this dictionary:
for k,v in dict_words.items():
print(k,v)
we obtain that for both keys we have the same value, i. e. [0,1,3]
.
It is incorrect - it should be for the key !,
the [0,1]
value and for the key Hey!
, the [3]
value.
Could anyone point me where the bug is and how to fix it? I would be grateful for help.