About bloggers : Former Internet manufacturer tencent staff , Network security giant Venustech staff , Alibaba cloud development community expert blogger , WeChat official account java Quality creators of basic notes ,csdn High quality creative bloggers , Entrepreneur , Knowledge sharers , Welcome to your attention , give the thumbs-up , Collection .
In the actual development process , We will encounter situations where we need to correlate relevant data , for example , Deal with student id 、 full name 、 Age 、 Grades and other information . in addition , There will also be situations where different objects that can be identified need to be considered as a whole .Python Two data structures, dictionary and set, are provided to solve the above problems . Here is an introduction python Access to dictionaries .
Each element in the dictionary represents a mapping relationship , Will provide “ key ” As a subscript, you can access the corresponding “ value ”, If this does not exist in the dictionary “ key ” An exception will be thrown . The syntax is as follows :
Dictionary variable name [ key ]
for example :
stu_info = {'num': '20180105', 'name': 'Yinbing', 'sex': 'male'} # Create a dictionary
print(stu_info['num']) # according to num Access student ID
print(stu_info['age']) # There is no exception thrown for the specified key
give the result as follows .
When accessing the dictionary , If you are not sure if there is a key in the dictionary , It can be done by get() Method to get , If the key exists , The corresponding value is returned , If it does not exist , Returns the default value . The syntax is as follows :
dict.get(key[,default=None]) for example :
stu_info = {'num': '20180105', 'name': 'Yinbing', 'sex': 'male'} # Create a dictionary
print(stu_info.get('name')) # get() Get student name
print(stu_info.get('age')) # get() Get student age , The return value is None
print(stu_info.get('age')) # Output return value None
print(stu_info.get('age', 18)) # Set the return default value to 18
give the result as follows .
1、 Liao Xuefeng's official website 2、python Official website 3、Python Programming case tutorial
The above is about python Access to dictionaries , You can refer to it , Relevant knowledge will be continuously updated later , Make progress together .