How to sort a tuple of elements in python, first on the basis of value and then on the basis of key. Consider the program in which I am taking input from the user as a string. I want to find out the count of each character and print the 3 most common characters in a string.
#input string
strr=list(raw_input())
count=dict()
#store the count of each character in dictionary
for i in range(len(strr)):
count[strr[i]]=count.get(strr[i],0)+1
#hence we can't perform sorting on dict so convert it into tuple
temp=list()
t=count.items()
for (k,v) in t:
temp.append((v,k))
temp.sort(reverse=True)
#print 3 most common element
for (v,k) in temp[:3]:
print k,v
on giving the i/p -aabbbccde
Output of the above code is:
3 b
2 c
2 a
But I want the output as:
3 b
2 a
2 c