Reputation: 57
My program that takes a string as an input from the user and counts the frequency of each character using the dictionary. Input:
Python programming is fun
Expected output:
{'p': 2, 'y': 1, 't': 1, 'h': 1, 'o': 2, 'n': 3, 'r': 2, 'g': 2, 'a': 1, 'm': 2, 'i': 2, 's': 1, 'f': 1, 'u': 1}
My code:
string = input().lower()
dicx = {}
count = 0
for i in string:
dicx['i'] = ''
print(dicx)
Upvotes: 0
Views: 11992
Reputation: 37
d = {}
test_str = input().lower()
for x in test_str:
d[x] = d.get(x,0) + 1
print(d)
much more elegant like this
Upvotes: 0
Reputation: 3
def charCounter(string):
empty = {}
for i in string.lower():
if i in empty.keys():
empty[i] += 1
else:
empty[i] = 1
return empty
print(charCounter("Oh, it is python"))
Upvotes: 0
Reputation: 1837
Way 1: For
symbols = {}
for s in inp_str.lower():
if s in symbols:
symbols[s] += 1
else:
symbols.update({s: 1})
print(symbols)
Way 2: defaultdict
symbols = defaultdict(int)
for s in inp_str.lower():
symbols[s] += 1
print(symbols)
Way 3: Counter
symbols = Counter(inp_str.lower())
print(symbols)
Upvotes: 0
Reputation: 34
Function takes input as string and counts the character and stores them in a dictionary
from typing import Dict
char_dict = {} #type: Dict[str, int]
def char_count(string: str) -> dict:
new_string = string.lower()
for c in new_string:
if c in char_dict:
char_dict[c] += 1
else:
char_dict[c] = 1
return char_dict
if __name__ == "__main__":
UserString = input("Enter Input String: ")
CharCount = char_count(UserString)
print("Characters Count: ", CharCount)
Example:
Enter Input String: Python programming is fun
Characters Count: {'p': 2, 'y': 1, 't': 1, 'h': 1, 'o': 2, 'n': 3, ' ': 3, 'r': 2, 'g': 2, 'a': 1, 'm': 2, 'i': 2, 's': 1, 'f': 1, 'u': 1}
Upvotes: 0
Reputation: 126
You can iterate over string and update the dictionary accordingly and also there's no need of any count variable.
test_str = input().lower()
dicx = {}
for i in test_str:
if i in dicx:
dicx[i] += 1
else:
dicx[i] = 1
print(dicx)
Upvotes: 0