0

I have written a function that counts the freq of characters in a file. The function works as intended, however, I would like to print the dictionary alphabetically by key. How do I do this the simplest way in Python.

Here is my function:

def characters(textfile):
    textfile=open(textfile)         
    characters={} 
    for line in textfile:
        for char in line:
            if char in characters:
                characters[char]+=1
            else:
                characters[char]=1

    print(characters)  
  • 3
    Does this answer your question? [How can I sort a dictionary by key?](https://stackoverflow.com/questions/9001509/how-can-i-sort-a-dictionary-by-key) – Marius Mucenicu Dec 18 '19 at 12:35
  • 1
    https://stackoverflow.com/a/9001529/4889267 – Alan Kavanagh Dec 18 '19 at 12:35
  • Hello! Does this answer your question? https://stackoverflow.com/questions/19650836/sort-a-dictionary-alphabetically-and-print-it-by-frequency –  Dec 18 '19 at 12:35
  • [Sorts dictionary with word count](https://thispointer.com/python-how-to-sort-a-dictionary-by-key-or-value/) – DarrylG Dec 18 '19 at 12:37

1 Answers1

1

I would turn it into a list and sort it

character_list = list(characters.items())
character_list.sort()
print(character_list)
Quinten C
  • 660
  • 1
  • 8
  • 18