Reputation: 88
I have to count the how many times a word is used in a sentence. I have found the solution, however i want the code to be more concise and want to solve it using dictionary comprehension. Can someone please help me understand what is wrong with the following code?
user_input = input().lower().split()
usage_dict = dict()
usage_dict = {word:usage_dict.get(word, 0) + 1 for word in user_input}
print(usage_dict)
Input : a aa abC aa ac abc bcd a
Output : {'a': 1, 'aa': 1, 'abc': 1, 'ac': 1, 'bcd': 1}
Expected Output: {'a': 2, 'aa': 2, 'abc': 2, 'ac': 1, 'bcd': 1}
Upvotes: 0
Views: 105
Reputation: 54168
The usage_dict
dictionnary is created once the dict-comprehension is ended, there is no concept of temporary state of the dict, so usage_dict.get(word, 0)
always gives 0
That is working only in a for loop:
usage_dict = {}
for word in user_input:
usage_dict[word] = usage_dict.get(word, 0) + 1
Use list.count()
usage_dict = {word: user_input.count(word) for word in set(user_input)}
Use collections.Counter
which uses the same for loop that above
usage_dict = Counter(user_input)
Upvotes: 3
Reputation: 71600
You could use a dictionary comprehension:
user_input = input().lower().split()
usage_dict = {word: user_input.count(word) for word in user_input}
print(usage_dict)
Or use collections.Counter
:
import collections
user_input = input().lower().split()
usage_dict = collections.Counter(user_input)
print(usage_dict)
Both codes output:
{'a': 2, 'aa': 2, 'abc': 2, 'ac': 1, 'bcd': 1}
The reason it doesn't work is because getting the count of value in the middle of a dictionary comprehension doesn't work, because it has to first finish the dictionary comprehension then assign it as a variable named usage_dict
.
Upvotes: 0
Reputation: 23815
Use Counter. See below
from collections import Counter
data = 'a aa abC aa ac abc bcd a'.split()
c = Counter(data)
print(c)
output
Counter({'a': 2, 'aa': 2, 'abC': 1, 'ac': 1, 'abc': 1, 'bcd': 1})
Upvotes: 0
Reputation:
Try to use Counter
from collections import Counter
user_input = input().lower().split()
usage_dict = Counter(user_input)
print(usage_dict)
Or:
usage_dict = {x:user_input.count(x) for x in user_input}
Returns
{'a': 2, 'aa': 2, 'abc': 2, 'ac': 1, 'bcd': 1}
Upvotes: 0