Search code examples
pythonlistalphabet

python get list element according to alphabet


I have a list of names alphabetically, like:

list = ['ABC', 'ACE', 'BED', 'BRT', 'CCD', ..]

How can I get element from each starting letter? Do I have to iterate the list one time? or Does python has some function to do it? New to python, this may be a really naive problem.

Suppose I want to get the second element from names that starts from 'A', this case I get 'ACE'.


Solution

  • If you're going to do multiple searches, you should take the one-time hit of iterating through everything and build a dictionary (or, to make it simpler, collections.defaultdict):

    from collections import defaultdict
    
    d = defaultdict(list)
    
    words = ['ABC', 'ACE', 'BED', 'BRT', 'CCD', ...]
    
    for word in words:
        d[word[0]].append(word)
    

    (Note that you shouldn't name your own variable list, as it shadows the built-in.)

    Now you can easily query for the second word starting with "A":

    d["A"][1] == "ACE"
    

    or the first two words for each letter:

    first_two = {c: w[:2] for c, w in d.items()}