-2

I'm trying to write a small program that will count a list of strings and print said strings in alphabetical order with the number of occurrences.

This is what I have so far:

from collections import Counter
def funct(list):
  count = Counter(list)
  print(count)

funct(['a','c','a','a','c','b'])

Current output is:

Counter({'a': 3, 'c': 2, 'b': 1})

How I can reformat the output including sorting the strings?

Desired output is:

a 3

b 1

c 2
jwpfox
  • 5,124
  • 11
  • 45
  • 42

2 Answers2

3
from collections import Counter
def funct(list):
  count = Counter(list)
  for item in sorted(count.items()):
      print(item[0], item[1])

funct(['a','c','a','a','c','b'])

OUTPUT:

a 3
b 1
c 2
0

you can use sorted function before printing it:

for keys,values in sorted(count.items()):
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
abhishek Sharma
  • 140
  • 2
  • 14