In this section we are going to discuss the dictionary data type.
We previously covered lists in python. Lists are one of several types of “data-structures” that python has built-in.
A data-structure is a way of arranging and organizing data in a computer program.
Python has several useful data-structures built in to the language.
One is a list
(which we already covered).
Another, which we cover in this lesson is the dictionary (dict
type).
Before we learn about dictionaries, we need to discuss the concept of mapping. Since we’re already familiar with lists, we’ll discuss how mapping works with lists first Mapping is the concept of assiciating a particular element (termed the “key”) to another element (termed the “value”).
When using lists, we could access particular elements by their index. For example:
>>> names = ['Russ', 'Lebron', 'Steph', 'Klay', 'Eric']
>>> names[0]
'Russ'
>>> names[1]
'Lebron'
>>> names[4]
'Eric'
One way of thinking about this is that each index (integer number) is associated with an element (string) in the list. Something like:
We use this association to access individual elements in the list. The number associated with each element is the position of the element in the list. Thus, lists have a mapping of “keys” to “values.” The keys of the data structure are the integer indexes of the list. Each index maps to a single value.
Dictionaries expand on this idea of mapping one value to another. However, with dictionaries, we are not limited to mapping index numbers to a value in the list. Instead we can map any type of value to any other type of value. In lists, the values may have any type, but the keys re limited to integers that correspond to valid list indexes. In dictionaries, both the keys and the values may be of any type!
When declaring a new dictionary, we must explicitly state which “keys” are associated with which “value”. Below is a very basic example, which ends up being very similar to a list since we are using numbers:
>>> names = { 0:'Russ', 1:'Lebron', 2:'Steph', 3:'Klay', 4:'Eric' }
>>> type(names)
<class 'dict'>
>>> print(names)
{0: 'Russ', 1: 'Lebron', 2: 'Steph', 3: 'Klay', 4: 'Eric'}
>>> names[0]
'Russ'
>>> names[2]
'Steph'
>>> names[4]
'Eric'
Notice a few things about this example:
names
is not a list
type, but a dict
(short for dictionary).:
).
The element on the left side of the colon is the key, and the element on the right side is the value.As already mentioned, when defining a dictionary we can use whatever values we want as the key for each value. Below are examples of using different keys for this same set of values.
Using each player’s number as the key:
>>> names = { 0:'Russ', 23:'Lebron', 30:'Steph', 11:'Klay', 2:'Eric' }
>>> names[0]
'Russ'
>>> names[23]
'Lebron'
>>> names[2]
'Eric'
>>> names[123]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 123
Using each player’s college as the key:
>>> names = { 'UCLA':'Russ', 'none':'Lebron', 'Davidson':'Steph', 'WSU':'Klay', 'UK':'Eric' }
>>> names['UCLA']
'Russ'
>>> names['Davidson']
'Steph'
>>> names['MISSING']
(error)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'MISSING'
>>> names[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 0
In some sense, dictionaries are a more flexible/powerful version of a python list (not to say that lists are not useful in their own right).
With dictionaries we can use the indexing syntax (square-brackets) to retrieve the value for a given key.
Several examples of this are demonstrated above.
We can also use this same syntax combined with an assignment (=
) to add a key/value pair to an already-existing dictionary.
>>> names = { 'UCLA':'Russ', 'WSU':'Klay', 'KU':'Eric' }
>>> print(names)
{'UCLA': 'Russ', 'WSU': 'Klay', 'KU': 'Eric'}
>>> names['UA'] = 'Andre'
>>> print(names)
{'UCLA': 'Russ', 'WSU': 'Klay', 'KU': 'Eric', 'UA': 'Andre'}
>>> names['DU'] = 'Kyrie'
>>> print(names)
{'UCLA': 'Russ', 'WSU': 'Klay', 'KU': 'Eric', 'UA': 'Andre', 'DU': 'Kyrie'}
Using this syntax, we were able to add two new key/value entries to the list. This syntax can also be used to change the value for a particular key. This happens automatically if we specify a key in the curly-braces that already exists.
>>> print(names)
{'UCLA': 'Russ', 'WSU': 'Klay', 'KU': 'Eric', 'UA': 'Andre', 'DU': 'Kyrie'}
>>> names['UCLA'] = 'Kevin'
>>> print(names)
{'UCLA': 'Kevin', 'WSU': 'Klay', 'KU': 'Eric', 'UA': 'Andre', 'DU': 'Kyrie'}
>>> names['UA'] = 'Aaron'
>>> print(names)
{'UCLA': 'Kevin', 'WSU': 'Klay', 'KU': 'Eric', 'UA': 'Aaron', 'DU': 'Kyrie'}
We can also remove key/value pairs from a dictionary using the pop
function.
>>> print(names)
{'UCLA': 'Kevin', 'WSU': 'Klay', 'KU': 'Eric', 'UA': 'Aaron', 'DU': 'Kyrie'}
>>> names.pop('WSU')
'Klay'
>>> print(names)
{'UCLA': 'Kevin', 'KU': 'Eric', 'UA': 'Aaron', 'DU': 'Kyrie'}
When writing and running programs, we can end up having dictionaries with many keys and values in them.
We don’t always know for sure when a list might have a key that we want to loop up.
In such cases, we want to check if a dictionary has a particular key before trying to access the values associated with the key.
We can do this with an if
statement and the in
keyword:
>>> names = {'UCLA': 'Russ', 'WSU': 'Klay', 'KU': 'Eric', 'UA': 'Andre', 'DU': 'Kyrie'}
>>> college = 'WSU'
>>> if college in names:
... print('The player who playes at ' + college + ' is ' + names[college] )
...
The player who playes at WSU is Klay
However, is we change college
to a college name that is not any key in the dictionary names
, the body of the if
statement will not execute:
>>> college = 'ASU'
>>> if college in names:
... print('The player who playes at ' + college + ' is ' + names[college] )
...
>>>
As with lists, it is sometimes useful to iterate over the key/value pairs in a dictionary with a loop. This can be accomplished with similar syntax to lists.
>>> names = {'UCLA': 'Russ', 'WSU': 'Klay', 'KU': 'Eric', 'UA': 'Andre', 'DU': 'Kyrie'}
>>>
>>> for key,value in names.items() :
... print('The key "' + key + '" maps to the value "' + value + '"')
...
The key "UCLA" maps to the value "Russ"
The key "WSU" maps to the value "Klay"
The key "KU" maps to the value "Eric"
The key "UA" maps to the value "Andre"
The key "DU" maps to the value "Kyrie"
Each time through the loop, the key
variable will be one of the keys in the dictionary, and the value
variable with be the corresponding value.
Write a function named keys_with_val
.
This function will take two arguments.
The first will be named dictionary
and will be a python dictionary.
The second will be named item
and will be a variable of any type.
This function should iterate through each key/value in dictionary
.
If item
is equal to both a key and value, print out “Both equal”.
Else if item
is equal to just the value, print out “val equal”.
Else if item
is equal to just the key, print out “key equal”.
Otherwise, print nothing.