0

Help me to understand! Why does the function append 1 for each key?

I need 1 to be added only by key to the corresponding list item. But the function adds 1 for each key. https://code.sololearn.com/cjdfPrSWZnrd/?ref=app

9th Apr 2020, 2:09 PM
Dmitry Bezruchko
Dmitry Bezruchko - avatar
3 Answers
+ 1
When you do (x[i] = value) on line 11 you put the reference to e in every key in x, therefore when you seemingly append 1 to one key's list, you, in fact, append to all of them and in the end you get a dict of n 1s for each key where n is how many words you get. To avoid that use x[i] = value[:], or the more readable, x[i] = value.copy(). Or... you could just rethink this more simply and write: words = input().lower().split() count_dict = {} for word in words: count_dict[word] = count_dict.get(word, 0) + 1 print(count_dict) Note: dict.get(key, default=None) does the following: if key in dict: return dict[key] else: return default This avoids a nasty KeyError. Refer to this discussion for more info: https://www.sololearn.com/Discuss/2235829/?ref=app
10th Apr 2020, 9:35 PM
Zuke
Zuke - avatar
+ 1
thank you very much! you really helped!
19th Apr 2020, 8:36 AM
Dmitry Bezruchko
Dmitry Bezruchko - avatar
0
Dmitry Bezruchko So, just recently I discovered Counter: >>> from collections import Counter >>> Counter('apple apple banana orange banana apple'.split()) Counter({'apple': 3, 'banana': 2, 'orange': 1}) Python was a good choice :)
20th Apr 2020, 3:50 PM
Zuke
Zuke - avatar