Sorting dict items¶
Let us understand how we can sort the dict items in Python.
dict
is nothing but group of key value pairs where keys are unique.sorted
ondict
returns only sorted keys.
In [7]:
famous_players = {
'Pete Sampras': 'Tennis',
'Sachin Tendulkar': 'Cricket',
'Brian Lara': 'Cricket',
'Diego Maradona': 'Soccer',
'Roger Federer': 'Tennis',
'Ian Thorpe': 'Swimming',
'Ronaldo': 'Soccer',
'Usain Bolt': 'Running',
'P. V. Sindhu': 'Badminton',
'Shane Warne': 'Cricket',
'David Beckham': 'Cricket',
'Michael Phelps': 'Swimming'
}
In [8]:
sorted(famous_players) # Creates list with only keys from dict
Out[8]:
['Brian Lara', 'David Beckham', 'Diego Maradona', 'Ian Thorpe', 'Michael Phelps', 'P. V. Sindhu', 'Pete Sampras', 'Roger Federer', 'Ronaldo', 'Sachin Tendulkar', 'Shane Warne', 'Usain Bolt']
In [9]:
type(sorted(famous_players)) # Creates list with only keys from dict
Out[9]:
list
- But at times we might want to sort the items based up on the values in the
dict
. - Here are the steps involved to sort the items in dict by values.
- Create list like object using
items
. - Sort the list like object using
sorted
with custom comparison or sort logic. We need to usekey
argument for that.
- Create list like object using
- The output of
sorted
will be of typelist
.
In [10]:
famous_players.items()
Out[10]:
dict_items([('Pete Sampras', 'Tennis'), ('Sachin Tendulkar', 'Cricket'), ('Brian Lara', 'Cricket'), ('Diego Maradona', 'Soccer'), ('Roger Federer', 'Tennis'), ('Ian Thorpe', 'Swimming'), ('Ronaldo', 'Soccer'), ('Usain Bolt', 'Running'), ('P. V. Sindhu', 'Badminton'), ('Shane Warne', 'Cricket'), ('David Beckham', 'Cricket'), ('Michael Phelps', 'Swimming')])
In [11]:
# Sorts based up on natural order of tuples
# By default data will be sorted by names of the players.
# Player names are first elemen in the tuples
sorted(famous_players.items())
Out[11]:
[('Brian Lara', 'Cricket'), ('David Beckham', 'Cricket'), ('Diego Maradona', 'Soccer'), ('Ian Thorpe', 'Swimming'), ('Michael Phelps', 'Swimming'), ('P. V. Sindhu', 'Badminton'), ('Pete Sampras', 'Tennis'), ('Roger Federer', 'Tennis'), ('Ronaldo', 'Soccer'), ('Sachin Tendulkar', 'Cricket'), ('Shane Warne', 'Cricket'), ('Usain Bolt', 'Running')]
In [12]:
# Use key argument to pass the custom comparison logic
# We would like to compare by sport name.
# Sport name is second elemet in tuple.
sorted(famous_players.items(), key=lambda player: player[1])
Out[12]:
[('P. V. Sindhu', 'Badminton'), ('Sachin Tendulkar', 'Cricket'), ('Brian Lara', 'Cricket'), ('Shane Warne', 'Cricket'), ('David Beckham', 'Cricket'), ('Usain Bolt', 'Running'), ('Diego Maradona', 'Soccer'), ('Ronaldo', 'Soccer'), ('Ian Thorpe', 'Swimming'), ('Michael Phelps', 'Swimming'), ('Pete Sampras', 'Tennis'), ('Roger Federer', 'Tennis')]
- You can see that data is sorted in ascending order by name of the sport now.