0

Is it possible in python to count letters and sort by character in string occurrence?

For example,

string = "Johnyjohny"

output:
{'J': 1, 'o': 2, 'h': 2, 'n': 2, 'y': 2, 'j': 1}

I can count it or sort it in alphabetical order.

def dictcode(str=""):
    str = "Johnyjohny"
    dict1 = dict((letter,str.count(letter)) for letter in set(str))

    return dict1

print(dictcode())
QmanW
  • 1
  • 2

1 Answers1

0

Dictionaries aren't really ordered and therefore can't really be 'sorted'. Instead you can do something like this:

sorted_dict = sorted(dictcode().items(), key=lambda x : x[1], reverse=True)

output: [('y', 2), ('h', 2), ('o', 2), ('n', 2), ('j', 1), ('J', 1)]

It returns a list of tuples, but that should be fine.

Will Metcher
  • 331
  • 1
  • 11