Process dict values¶
Let us understand how we can process the values in dicts.
- We have already seen a function called as
values
which return all the values as a list like object.
In [1]:
order_item_subtotals = {
1: 299.98,
2: 199.99,
3: 250.0,
4: 129.99
}
In [2]:
order_item_subtotals
Out[2]:
{1: 299.98, 2: 199.99, 3: 250.0, 4: 129.99}
In [3]:
type(order_item_subtotals)
Out[3]:
dict
In [4]:
order_item_subtotals.values()
Out[4]:
dict_values([299.98, 199.99, 250.0, 129.99])
In [5]:
type(order_item_subtotals.values())
Out[5]:
dict_values
- If we would like to get total revenue by adding all the values, we can apply
sum
.
In [6]:
sum(order_item_subtotals.values())
Out[6]:
879.96
In [7]:
# min
min(order_item_subtotals.values())
Out[7]:
129.99
In [8]:
# max
max(order_item_subtotals.values())
Out[8]:
299.98
In [9]:
# sort
sorted(order_item_subtotals.values())
Out[9]:
[129.99, 199.99, 250.0, 299.98]
- We can convert the values to
list
and perform all available list operations.
In [10]:
list(order_item_subtotals.values())
Out[10]:
[299.98, 199.99, 250.0, 129.99]
- The values in the
dict
need not be unique. Sometimes, we might want to get all the unique values. - For example, get all the unique sports that is part of this dict. In this
dict
, the key is name of the sports person and the value is the sport the person plays.
{note}
You can always use `set` to get unique elements from any list type object.
In [11]:
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 [12]:
famous_players.values()
Out[12]:
dict_values(['Tennis', 'Cricket', 'Cricket', 'Soccer', 'Tennis', 'Swimming', 'Soccer', 'Running', 'Badminton', 'Cricket', 'Cricket', 'Swimming'])
In [13]:
len(famous_players.values())
Out[13]:
12
In [14]:
set(famous_players.values())
Out[14]:
{'Badminton', 'Cricket', 'Running', 'Soccer', 'Swimming', 'Tennis'}
In [15]:
len(set(famous_players.values()))
Out[15]:
6