how to sort a list of tuples by first element (string) alphabetically [PYTHON]

15,392

Solution 1

As Zero points out, your example data isn't valid, but I presume this is simply a typing issue. So providing the data is valid and looks like:

my_data = [('peter',1), ('mary',5), ('anthony',6), ('brandon',4)]

You could use either

sorted_data = sorted(my_data)

or:

my_data.sort()

Solution 2

To sort your list in place, just sort() it :

>>> lst = [('peter',1), ('mary',5), ('anthony',6), ('brandon',4)]
>>> lst.sort()
>>> lst
[('anthony', 6), ('brandon', 4), ('mary', 5), ('peter', 1)]

It will sort the tuples by their first element (the name). If two names are the same, they will be sorted by their second element (the id). See "Lexicographical order".

If you have a dict, you can get a sorted list of tuples this way :

>>> dct = {'peter': 1, 'mary': 5, 'anthony':6, 'brandon':4}
>>> sorted(dct.items())
[('anthony', 6), ('brandon', 4), ('mary', 5), ('peter', 1)]

Solution 3

I think you mean to say this:

z = [('peter',1), ('mary',5), ('anthony',6), ('brandon',4)]

You can try:

from operator import itemgetter
sorted(z, key = itemgetter(0))

Or:

sorted(z, key = lambda x: x[0])

Or:

z.sort(key = lambda x: x[0])

In case you are referring to a dictionary which would look like this:

z1 = {'peter':1, 'mary':5, 'anthony':6, 'brandon':4}

Dictionaries are inherently order-less and sorting dictionaries does not makes sense. We use keys to reference dictionary elements, thus the order would not matter.

You can refer to http://sthurlow.com/python/lesson06/ for inherent differences between a list, tuple and dictionary.

Share:
15,392
py_9
Author by

py_9

Updated on July 17, 2022

Comments

  • py_9
    py_9 almost 2 years

    I have a list of tuples like this:

    [('peter':1), ('mary':5), ('anthony':6), ('brandon':4)]
    

    if I wanted to sort this list and get something like:

    [('anthony':6),('brandon':4),('mary':5),('peter':1)]
    

    How could I sort this in python ?

  • Zero Piraeus
    Zero Piraeus about 7 years
    Assuming OP has an actual list of tuples, the key argument is unnecessary. sorted() sorts lexicographically by default.