Skip to content

Instantly share code, notes, and snippets.

@cameronp98
Created January 9, 2014 22:01
Show Gist options
  • Save cameronp98/8342869 to your computer and use it in GitHub Desktop.
Save cameronp98/8342869 to your computer and use it in GitHub Desktop.
Sorting by letter frequency in Python using defaultdict
from collections import defaultdict
def letter_frequency(text):
freq = defaultdict(int)
for char in text.replace("\n", ""):
freq[char] += 1
return freq
def main():
text = "The quick brown fox jumps over the lazy dog"
freq = letter_frequency(text.lower())
print(sorted(freq.items(), key=lambda i: i[1], reverse=True))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment