Haloxx
Haloxx

Reputation: 45

How do I sort an array into multiple arrays alphabetically

I'm trying to sort an array into multiple arrays by their starting letter

this is an example

list1 = ["apple", "banana", "carrot", "avocado"]

into this

a = ["apple", "avocado"]
b = ["banana"]
c = ["carrot"]

Upvotes: 1

Views: 71

Answers (4)

Deepak Tripathi
Deepak Tripathi

Reputation: 3233

Use itertools.groupby

from itertools import groupby
list1 = ["apple", "banana", "carrot", "avocado"]
print([list(val) for _, val in groupby(sorted(list1), key=lambda x: x[0])])
# [['apple', 'avocado'], ['banana'], ['carrot']]
# IF want dictionary 
print({k : list(val) for k, val in groupby(sorted(list1), key=lambda x: x[0])})
# {'a': ['apple', 'avocado'], 'b': ['banana'], 'c': ['carrot']}

Upvotes: 3

T C Molenaar
T C Molenaar

Reputation: 3260

As all the answers suggest, it is better to use a dictionary for this instead of making a lot of variables (and easier!). You can make this dictionary by looping over all fruits and add them to the right key (first letter).

list1 = ["apple", "banana", "carrot", "avocado"]

d = {}

for item in list1:
    key = item[0]
    if key in d.keys(): # if key already exists: append to list
        d[key].append(item)
    else: # if key does not exist: make new list
        d[key] = [item]

Output:

{'a': ['apple', 'avocado'], 'b': ['banana'], 'c': ['carrot']}

Now you can get all fruits with letter a by doing d['a'].

Upvotes: 3

matszwecja
matszwecja

Reputation: 7970

It's techincally not sorting, but categorising.

You can use a dictionary keyed by the first letter:

from collections import defaultdict

list1 = ["apple", "banana", "carrot", "avocado"]

d = defaultdict(list)
for el in list1:
    d[el[0]].append(el)

print(dict(d)) # {'a': ['apple', 'avocado'], 'b': ['banana'], 'c': ['carrot']}

Resulting dict will contain lists for each letter, e.g d["a"] = ["apple", "avocado"]

Upvotes: 2

Rabinzel
Rabinzel

Reputation: 7923

It is propably better to save the seperate lists in a dictionary since you don't have to define variables by hand. Like this you can scale the number of elements in the list up.

dic = {}
for elem in list1:
    dic.setdefault(elem[0], []).append(elem)

print(dic)
{'a': ['apple', 'avocado'], 'b': ['banana'], 'c': ['carrot']}

Upvotes: 2

Related Questions