python String Count

I want to count the occurence of a string in a given list than print it in alphabetically order.
For example. I love my mom and I love my dad.
Result:
and:1
dad:1
I:2
love:2
mom:1
my:2

I am trying with this code.
from collections import Counter
z = [‘I’, ‘love’, ‘my’, ‘mom’, ‘and’, ‘I’,‘love’,‘my’,‘dad’]
Counter(z)
Counter({‘love’: 2, ‘I’: 2, ‘my’: 2, ‘and’: 1, ‘dad’: 1, ‘mo’: 1})

You can do z.count(‘element’) thus should do

  • a=[str(x) for x in raw_input().split()] a.sort()
  • a.append(’#’)
  • c=1
  • for i in range(len(a)-1):
  • if a[i]==a[i+1]:
  • c+=1
  • else:
  • print a[i]+’:’+str©
  • c=1

You can sort the counter based on the keys (i.e. the words here).

c=Counter(z)
l=sorted(c.items(), key=lambda x : x[0].lower())

Here, l is a list of tuples. In your case,its value will be:

[(‘and’, 1), (‘dad’, 1), (‘I’, 2), (‘love’, 2), (‘mom’, 1), (‘my’, 2)]

Note: From your question I have assumed that you want case-independent sorting of the strings.