Created
June 28, 2011 04:45
-
-
Save chooper/1050517 to your computer and use it in GitHub Desktop.
Group words by their first letter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
"""Group words by their first letter""" | |
from collections import defaultdict | |
def group_by_letter(words): | |
buckets = defaultdict(lambda:[]) | |
for word in words: | |
buckets[word[0].lower()].append(word) | |
return buckets | |
if __name__ == '__main__': | |
print group_by_letter(['narragansett','brooklyn lager','magic hat','dog fish head','shock top','ten penny','bass']) | |
# Output: defaultdict(<function <lambda> at 0x7fc83416b2a8>, {'b': ['bass', 'brooklyn lager'], 'd': ['dog fish head'], 'm': ['magic hat'], 'n':['narragansett'], 's': ['shock top'], 't': ['ten penny']}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment