Great job on the dictionary.
> characters
# {'s': 8, ' ': 7, 'l': 6, 'e': 6, 'a': 3, 'h': 3, 'y': 2, 'b': 1, 't': 1, 'o': 1, 'r': 1}
Sort those dictionary keys (tuples) by value.
characters.items()
are the items in your dictionary as (key, value)
tuples.
sorted(dictionary.items(), key=function)
will sort those tuples, but we'll want a key
function to tell sorted
how to sort them.
We define a lambda function to sort by item[1]
. The lambda function accepts a (key, value) tuple and returns (key, value)[1], which is the value. That way sorted()
will know to sort by the second item in the tuple.
Here's are your sorted tuples:
> sorted(characters.items(), key=lambda x: x[1])
# [('b', 1), ('t', 1), ('o', 1), ('r', 1), ('y', 2), ('a', 3), ('h', 3), ('l', 6), ('e', 6), (' ', 7), ('s', 8)]
Select the last tuple [-1]
. Select the key.[0]
> best_char = sorted(characters.items(), key=lambda x: x[1])[-1][0]
# s
> worst_char = sorted(characters.items(), key=lambda x: x[1])[0][0]
# b or t or o or r. There are four characters that appear only once.