I don't know how to order a list of letters and their frequencies in ascending order i.e {'z':1, 'g':3, 'a':5, and so on}
I'm trying to recreate the Huffman Algorithm, a lossless compression algorithm, in Python. txt
is a string of text, that was been split up so each letter, including spaces, is an individual index. I have tried using Counter(txt)
, which finds how many times each letter appears in txt
and creates a dictionary. But this orders the dictionary from highest frequency to lowest frequency, and I need it to be vice-versa, so that it follows the steps of Huffman Algorithm. I then tried adding
for key, value in sorted(freq.iteritems(), key=lambda(k,v): (v,k)):
print("%s: %s" % (key, value))
However this creates a syntax error, and I dont know if this is the best way to do it.
Here is my code:
from collections import Counter
def huffman(file):
txt = list(map(lambda c2: c2, file)) # Places each individual char into array.
freq=Counter(txt) #Counts numb of times a letter appears.
print(freq)
for key, value in sorted(freq.iteritems(), key=lambda(k,v): (v,k)):
print("%s: %s" % (key, value))
I just need the freq
dictionary to be order from least common to most common so that it follows the steps of Huffman's algorithm. So instead of {'a':5, 'g':3, 'z':1}
it is {'z':1, 'g':3, 'a':5}