-1

I have a string and i've created a dictionary from the string, now i need to find the most frequent letter based on this dictionary and assign the letter to the variable best_char. And also the least frequent letter to the variable worst_char.

sally = "sally sells sea shells by the sea shore"
characters = {}
for i in sally:
    characters[i]=characters.get(i,0)+1
Lefteris Theodorou
  • 91
  • 1
  • 4
  • 12

1 Answers1

0

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.
Shay
  • 1,368
  • 11
  • 17
  • here i'll give you the questions: Create the dictionary characters that shows each character from the string sally and its frequency. Then, find the most frequent letter based on the dictionary. Assign this letter to the variable best_char. – Lefteris Theodorou Apr 17 '19 at 18:14
  • @LefterisTheodorou The Counter bit is a shortcut for the work you've already done. After that, you'll sort the dictionary.items() as I've described. The least frequent will be the first item in the sorted items, the most frequent will be the last item. – Shay Apr 17 '19 at 18:20
  • sorry but its not working for me i'm very new I don't know how to add it all up. – Lefteris Theodorou Apr 17 '19 at 18:41
  • You'll only need the last code line in my answer. Place that line under your code, and everything will work. Then you can re-read and play around a bit to see HOW it works. – Shay Apr 17 '19 at 20:50