0

how to order charters of a descending order? if similar apathetically. frequency first then alphabetical series .

#!/user/bin/python3
# -*- coding: utf-8 -*-
import string
text = """
Mississippi
"""
# create a character: frequency dictionary
charFreqDic = {}
for char in text.upper():
    charFreqDic[char] = charFreqDic.get(char, 0) + 1
print ("Characters sorted by ASCII number:")
# create a sorted list of keys
key_list = sorted(charFreqDic.keys())
for key in key_list:
    # don't show space and newline
    if key not in " \n":
        # associate the value with the key
        print ("%2s  %3d" % (key, charFreqDic[key]))

print ("Characters sorted by frequency:")
print("\n")
print("No Occur"+"\t "+ "Character")
# convert charFreqDic to list of (k, v) tuples with charFreqDic.items()
# flip tuple elements to (v, k) using list comprehension
# then sort list of tuples (order is v,k), highest v first

#dictionary to list
copytolist=[]
for K,V in charFreqDic.items():
    copytolist.append((V,K));
copytolist=sorted(copytolist,reverse=True)
print(copytolist)
print("Words sorted by frequency:")
print("\n")
print("No Occur" + "\t " + "Word")
for K in copytolist:
    if K[1] not in " \n":
        print(str(K[0]) + "\t\t\t " + str(K[1]) + "'s")

output is Words sorted by frequency:

No Occur     Word
4            S's
4            I's
2            P's
1            M's

But I wanted the output to be ordered both based on frequency and based on alphabetical series if frequency is similar.

No Occur     Word
4            I's
4            S's
2            P's
1            M's
Cœur
  • 37,241
  • 25
  • 195
  • 267
  • 3
    Possible duplicate of [How can I sort tuples by reverse, yet breaking ties non-reverse? (Python)](http://stackoverflow.com/questions/18414995/how-can-i-sort-tuples-by-reverse-yet-breaking-ties-non-reverse-python) – yeputons Feb 03 '17 at 08:29
  • Please [read this community discussion](http://meta.stackoverflow.com/q/326569/472495) about begging in questions. – halfer Feb 03 '17 at 08:36

0 Answers0