We already know that list and tuple can be used to represent sequential collections, for example, the name of the class:
[' Adam ', ' Lisa ', ' Bart ']
Or the test results list:
[95, 85, 59]
However, to find the corresponding score according to the name, it is inconvenient to use two list to indicate.
If you associate a name with a score, make a similar look-up table:
' Adam ' ==> ' Lisa ' ==> ' Bart ' ==> 59
Given a name, you can find the score directly.
Python's dict is dedicated to doing this. The lookup table for "name"-"score" is shown in dict as follows:
D = { ' Adam ': +, ' Lisa ': $, ' Bart ': 59}
We call the name key, the corresponding result is called value, Dict is the key to find value.
The curly braces {} indicate that this is a dict, and then follow the key:valueand write them out. The last comma of a key:value can be omitted.
Since Dict is also a collection, thelen () function can calculate the size of any collection:
>>> Len (d) 3
Note: a key-value is counted one, so the dict size is 3.
Task
The new Paul students score is 75 points, please write a dict, the results of Paul's students also added in.
D = { ' Adam ': +, ' Lisa ': $, ' Bart ': 59}
Reference code:
D = {
' Adam ': 95,
' Lisa ': 85,
' Bart ': 59,
' Paul ': 75
}
Python's visit to Dict
We have been able to create a dict that represents the correspondence between the name and the score:
D = { ' Adam ': +, ' Lisa ': $, ' Bart ': 59}
So, how to find the corresponding score according to the name?
You can simply use the form of D[key] to find the corresponding value, which is like the list,but the list must return the corresponding element using the index, and Dict uses key:
>>> print d[' Adam ']95>>> print d[' Paul ']traceback (most recent call last): File "index.py", line 11 , in <module> print d[' Paul ']keyerror: ' Paul '
Note: The value of dict is accessed by key, and Dict returns the corresponding value as long as the key exists. If key does not exist, it will directly error: Keyerror.
There are two ways to avoid keyerror:
First, determine whether the key exists, with the in operator:
If ' Paul ' in D: print d[' Paul '
If ' Paul ' is not present, the IF statement evaluates to False, and the print d[' Paul ' is not executed naturally, thus avoiding the error.
The second is to use the dict itself to provide a get method, when the key does not exist, return to none:
>>> print d.get (' Bart ') 59>>> print d.get (' Paul ') None
Task
According to the following dict:
D = { ' Adam ': +, ' Lisa ': $, ' Bart ': 59}
Please print out:
adam:95lisa:85bart:59
Reference code:
D = {
' Adam ': 95,
' Lisa ': 85,
' Bart ': 59
}
For key in [' Adam ', ' Lisa ', ' Bart ']:
Print "%s:%d"% (key, D[key])
Or
D = {
' Adam ': 95,
' Lisa ': 85,
' Bart ': 59
}
Print "Adam:", D.get (' Adam ')
Print "Lisa:", d[' Lisa '
If ' Bart ' in D:
Print "Bart:", d[' Bart ')
What Python is Dict