Home > other >  count the number of times each alphabet appears in a word using dictionary
count the number of times each alphabet appears in a word using dictionary

Time:11-16

i already found the solution

s= input("input string: ")

for n in s:
  print({n:s.count(n)})

output :

input string: chocolate coco

{'c': 4} {'h': 1} {'o': 4} {'c': 4} {'o': 4} {'l': 1} {'a': 1} {'t': 1} {'e': 1} {' ': 1} {'c': 4} {'o': 4} {'c': 4} {'o': 4}

but how i can make the output doesnt repeat the alphabet. i want to have the output to be like this :

{'c': 4} {'h': 1} {'o': 4} {'c': 4} {'o': 4} {'l': 1} {'a': 1} {'t': 1} {'e': 1} {' ': 1}

CodePudding user response:

Try this:

s= input("input string: ")

for n in set(s):
  print({n:s.count(n)})

set gives all of the values without repetitions. This means your code will now not print out duplicate letters.

CodePudding user response:

s= input("input string: ")
d=dict()
for n in s:
    if n in d:
        d[n] =1
    else:
        d[n]=1
print(d)

output

input string: Python is an interpreted high-level general-purpose programming language
{'P': 1, 'y': 1, 't': 3, 'h': 3, 'o': 3, 'n': 6, ' ': 7, 'i': 4, 's': 2, 'a': 5, 'e': 9, 'r': 6, 'p': 4, 'd': 1, 'g':
6, '-': 2, 'l': 4, 'v': 1, 'u': 2, 'm': 2}

CodePudding user response:

You can also do it like this:-

dict = {}
text = input()
for letter in text:
    dict[letter] = text.count(letter)
print (dict)

CodePudding user response:

inorder to get non-duplicated as well as in utf value order you can do it like this:

>>> s= input("input string: ")
input string: qwertyuiop lorem doge milk honeybee
>>> mydict = {n:s.count(n) for n in s}
>>> for e in sorted(mydict):
...     print(f"{e}: {mydict[e]}")
... 

output:

 : 4
b: 1
d: 1
e: 6
g: 1
h: 1
i: 2
k: 1
l: 2
m: 2
n: 1
o: 4
p: 1
q: 1
r: 2
t: 1
u: 1
w: 1
y: 2
  • Related