For example, I am trying to count the amount of times a letter appears in my input. Also, I'm trying to use the tools I've learned so far. I haven't learned the .count tools in the course I'm taking so far.
1st I run this code:
any_word = input()
char_amount = {}
for i in any_word:
char_amount[i] = len(i)
print(char_amount)
My input is: hello
The result is this: I get every time is below and my if statements fail to update the key for 'l'
to 2
.
{'h': 1, 'e': 1, 'l': 1, 'o': 1}
My if statements fail to update the key for 'l'
to 2
. I cant figure out the logic to an if statement to add 1
to the 'l'
key because the duplicate is recognized in every key and the result is below. I assume i need another variable but i can't think up the logic. Thanks for any help:
{'h': 2, 'e': 2, 'l': 2, 'o': 2}
CodePudding user response:
You should really be using the Counter class from the collections module:
from collections import Counter
value = input('Enter some text: ')
counter = Counter(value)
print(counter)
Thus, for an input of 'hello' you'd get:
Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})
Counter subclasses dict so you can access it just like any other dictionary
CodePudding user response:
Use char_amount[i] = char_amount.get(i, 0) 1
- this will try to get key i
from dict char_amount
, if not found returns 0
. Then increases the value of this key by 1
any_word = input()
char_amount = {}
for i in any_word:
char_amount[i] = char_amount.get(i, 0) 1
print(char_amount)
Prints:
hello
{'h': 1, 'e': 1, 'l': 2, 'o': 1}
CodePudding user response:
Without collections Module:
word = input()
char_amount = {}
for char in word:
if char not in char_amount:
char_amount[char] = 1
else:
char_amount[char] = 1
print(char_amount)
Using collections module:
from collections import Counter
print(Counter(input()))
CodePudding user response:
use built in counter
from collections import Counter
my_counter = Counter("hello")
print(my_counter)
Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})