Sort Python dict in various ways

Original Data

world_cup_wins = {
    "Brazil": 5,
    "Germany": 4,
    "Italy": 4,
    "Argentina": 2,
    "France": 2,
    "Uruguay": 2,
    "England": 1,
    "Spain": 1
}

SORT DICTIONARY BY KEY ASCENDING

for key, value in sorted(world_cup_wins.items(), key=lambda x: x[0]):
    print(key, value)

Output:

Argentina 2
Brazil 5
England 1
France 2
Germany 4
Italy 4
Spain 1
Uruguay 2

SORT DICTIONARY BY KEY DESCENDING

for key, value in sorted(world_cup_wins.items(), key=lambda x: x[0], reverse=True):
    print(key, value)

Output:

Uruguay 2
Spain 1
Italy 4
Germany 4
France 2
England 1
Brazil 5
Argentina 2

SORT DICTIONARY BY VALUE ASCENDING

for key, value in sorted(world_cup_wins.items(), key=lambda x: x[1]):
    print(key, value)

Output:

Spain 1
England 1
Uruguay 2
Argentina 2
France 2
Italy 4
Germany 4
Brazil 5

SORT DICTIONARY BY VALUE DESCENDING

for key, value in sorted(world_cup_wins.items(), key=lambda x: x[1], reverse=True):
    print(key, value)

Output:

Brazil 5
Italy 4
Germany 4
Uruguay 2
Argentina 2
France 2
Spain 1
England 1

SORT DICTIONARY BY VALUE ASCENDING AND THEN BY KEY ASCENDING

for key, value in sorted(world_cup_wins.items(), key=lambda x: (x[1], x[0])):
    print(key, value)

Output:

England 1
Spain 1
Argentina 2
France 2
Uruguay 2
Germany 4
Italy 4
Brazil 5

SORT DICTIONARY BY VALUE DESCENDING AND THEN BY KEY ASCENDING

for key, value in sorted(world_cup_wins.items(), key=lambda x: (-x[1], x[0])):
    print(key, value)

Output:

Brazil 5
Germany 4
Italy 4
Argentina 2
France 2
Uruguay 2
England 1
Spain 1

Reference

Advertisement

Citation

Click to select citation style

Shovon, A. R. (2018, May 7). Sort Python Dictionary. Ahmedur Rahman Shovon. Retrieved June 22, 2024, from https://arshovon.com/blog/python-sort-dictionary/

Shovon, Ahmedur Rahman. “Sort Python Dictionary.” Ahmedur Rahman Shovon, 7 May. 2018. Web. 22 Jun. 2024. https://arshovon.com/blog/python-sort-dictionary/.

@misc{ shovon_2018,
    author = "Shovon, Ahmedur Rahman",
    title = "Sort Python Dictionary",
    year = "2018",
    url = "https://arshovon.com/blog/python-sort-dictionary/",
    note = "[Online; accessed 22-June-2024]"
}
Sort Python Dictionary