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