user20473020
user20473020

Reputation: 41

Alphabetically sorting tuples in a list using two parameters

I have a list of tuples of [(city name, country name), ...].

I'm trying to sort the list alphabetically so that the country names are ordered A-Z, and then if there is more than one city in that country, the cities in that country are then also ordered alphabetically.

So far I've tried using sorted() with a lambda function (below), but it doesn't seem to work. I'm pretty new to Python, so any help would be massively appreciated!!

sorted(list, key=lambda element: (element[0], element[1]))

Upvotes: 2

Views: 27

Answers (2)

Rodrigo Rodrigues
Rodrigo Rodrigues

Reputation: 8556

By default, python sorts tuples by applying the default sorting on the first element, than if it is a tie, on the second, and so on.

In your case, you seem to want to sort first on the second element, then on the first. Also, you probably want to ignore case, and sort austria before Belorus (which will not happen by default, python sorts string by ascii code).

You can try this:

data = [
    ("New york", "United States"),
    ("Rio de Janeiro", "brazil"),
    ("brasilia", "Brazil")
]

sorted(data, key=lambda x: (str.casefold(x[1]), str.casefold(x[0])))

Upvotes: 1

Andrej Kesely
Andrej Kesely

Reputation: 195478

If I understand your question correctly, just reverse the order of elements in the key function:

lst = [
    ("Prague", "Czech Republic"),
    ("Bratislava", "Slovakia"),
    ("Brno", "Czech Republic"),
]

print(sorted(lst, key=lambda t: (t[1], t[0])))

Prints:

[
    ("Brno", "Czech Republic"),
    ("Prague", "Czech Republic"),
    ("Bratislava", "Slovakia"),
]

Upvotes: 2

Related Questions