There are several issues in you code.
dictionary
is not ordered (though in some latest python versions it do preserve the order you add to it), so sorting it makes no sense actually. When you apply sorted
to a dictionary
, it returns the keys list
. Considering you need both key
and value
in the print, sorting .items()
is better choice. example:
d = {'b': 2, "a": 1}
print(sorted(d))
# ['a', 'b']
print(sorted(d.items()))
# [('a', 1), ('b', 2)]
sorted
function has a key
parameter, which is often a lambda expression indicating what property of the item to order by. If not specified, will sort by dictionary.key
by default, but in your case you want sort by dictionary.value
, so you need the key=
parameter.
- Sorted object is never used.
import collections
MY_FUN_STR = filter(str.isalpha, (str.lower("ThE_SLATe-Maker")))
frequencies = collections.Counter(MY_FUN_STR)
sorted_key_value_items = sorted(frequencies.items(), reverse=True, key=lambda x: x[1])
for letter, count in sorted_key_value_items:
print('{} appears {}'.format(letter, count) + " times")
Reference this answer to sort a dict: How do I sort a dictionary by value?