I have to get count of consonants present in given string
but seems like something missing. What i need to modify to get the expected result
My code :
var = 'aaeouAIyuiodffgXUEEE'
vowels='aeiou'
for i in vowels:
if i is not var:
print(var)
Expected result:
y 1
d 1
f 2
g 1
x 1
>Solution :
You can use collections.Counter for this job. It’s a dict subclass where each element is stored as dictionary keys and their counts are stored as dictionary values. So you can access the counts like:
>>> counts['y']
1
Then use sorted function on tuples of key-value pairs to sort the letters by alphabetical order and use dict constructor to re-construct the dictionary.
from collections import Counter
var = 'aaeouAIyuiodffgXUEEE'
vowels='aeiou'
counts = Counter([x for x in var.lower() if x not in vowels])
counts = dict(sorted(counts.items()))
Output:
{'d': 1, 'f': 2, 'g': 1, 'x': 1, 'y': 1}