I tried to define a function to print the letters of a word in decreasing order of their frequency, using dictionary and tuple. Two similar questions were Counting repeated characters in a string in Python and How to write a function that takes a string and prints the letters in decreasing order of frequency?, but the difference is the sorting (by frequency) part and the algorithm.
Here's what I wrote :-
def most_frequent(string):
d = dict() #Created a dictionary
for c in string:
d[c] = d.get(c,0)+1 #Employed the get method to get the value of the key c
t = d.items() #Created a list of tuples of key-value pairs
for letter, frequency in t:
letter, frequency = frequency, letter #Swapped the elements of the tuples
t.sort(reverse = True) #Sorting in descending order
for frequency, letter in t:
print (frequency," ",letter)
The error message produced when I call the function with "bookshopkeeper" as the argument is :-
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
most_frequent("bookshopkeeper")
File "<pyshell#1>", line 8, in most_frequent
t.sort(reverse = True)
AttributeError: 'dict_items' object has no attribute 'sort'
I used the get method to eliminate use of if conditionals. I am using python 3.3. Please fix the code. Thanks a lot.