Home > front end >  How would I make a Horizontal list into a vertical list
How would I make a Horizontal list into a vertical list

Time:07-07

How would I make it so that my vowel counter returns a vertical list instead of a horizontal list. Every time I use \n it just gives me an error I have no clue what I am doing wrong, I am a beginner coder and still have problems solving this. I have tried looking for an answer and I haven't found any. Could anybody help? So instead of looking like this {'a': 1, 'e': 1, 'i': 2, 'o': 1, 'u': 1}.

How do I make it look vertical like this

'a': 1 
'e': 1 
'i': 2 
'o': 1 
'u': 1
def count_vowels(string, vowels):
 string = string.casefold()
 count = {}.fromkeys(vowels, 0)

# To count the vowels
 for character in string:
     if character in count:
         count[character]  = 1
 return count
vowels = ("a", "e", "i", "o", "u")
string = "Counting all the strings"
print(count_vowels(string, vowels))

CodePudding user response:

If you want something other than Python's default formatting, then you have to do it yourself:

vowels = ("a", "e", "i", "o", "u")
string = "Counting all the strings"
for k,v in count_vowels(string, vowels).items():
    print( f"{k}: {v}" )

CodePudding user response:

By casting the dictionary to string and slice (or strip) the brackets should work:

...
string = "CoUnting All the strings"
counter = count_vowels(string)

print(*str(counter).strip('{}').split(', '), sep='\n')
#'a': 1
#'e': 1
#'i': 2
#'o': 1
#'u': 1

CodePudding user response:

Maybe this is what you want. Try to use collections module Counter to do a quick counts then match the vowels in the set() which should be faster. Then finally build up the dictionary using dictionary Comprehension and return it. Of course, you could combine all steps into one to make it more compact, if you like it.

Edit. Refactor the code based on OP's new changed requirements just now.

from collections import Counter

def count_vowels(string, vowels):
    counts = Counter(string)
    vowel_counts = {ch: cnt for ch, cnt in counts.items() if ch in vowels}
    
    return vowel_counts

# running it
vowels = set('aeiou')
string = "Counting all the strings"

counts = count_vowels(string, vowels)

for ch, count in counts.items():
    print(ch, count)

Output:

o 1
u 1
i 2
a 1
e 1
  • Related