Data type Partitioning
- Immutable data types (hash): tuples, bool, int, str
- Variable data type (non-hashed): list, dict, set
Dictionary Dict
A dictionary is the only type of mapping in Python that stores data in the form of key-value pairs (key-value). Python computes the hash function of key and determines the storage address of value based on the computed result, so the dictionary is stored out of order and the key must be hashed. A hash indicates that a key must be an immutable type, such as a number, a string, a tuple.
The Dictionary (dictionary) is the most flexible built-in data structure type in Python, except for lists. A list is an ordered combination of objects, and a dictionary is a collection of unordered objects. The difference between the two is that the elements in the dictionary are accessed by keys, not by offsets.
- Dictionary Operations-Add
DIC = {' Age': 18,'name':'Jin','Sex':'male'}dic[' Age'] = 15#When an age key value pair is already in the dictionary, the action is to modify the value>>>{'name':'Jin',' Age': 15,'Sex':'male'}dic['Nero'] = 30#When there is no Nero key-value pair in the dictionary, the operation is to add Nero key-value pairs to the dictionary>>>{' Age': 18,'Sex':'male','Nero': 30,'name':'Jin'}dic. SetDefault ('Ray','Hey')#When there is no Ray key pair in the dictionary, the ray key value pair is added to the dictionary, such as adding only keys without values, the default value is NoneDic.SetDefault('Ray', 10)#When a ray key pair is already in the dictionary, no action is taken and the original value is not overwritten>>>{' Age': 18,'name':'Jin','Ray':'Hey','Sex':'male'}
- Dictionary Operations-Delete
DIC = {' Age': 18,'name':'Jin','Sex':'male'}dic.pop ('name')#specify the key value to delete, you can enter only key>>>{' Age': 18,'Sex':'male'}dic.popitem ()#randomly deletes a key-value pair>>>{'Sex':'male','name':'Jin'}deldic[' Age']#Specify the key value delete, the key value does not exist the error>>>{'name':'Jin','Sex':'male'}dic.clear ()#Empty Dictionary>>>{}
- Dictionary operation-Change
Dic1 = {'Nero': 30,'Hobby':'Girl','Sex':'Mans',' Age': 18}dic= {' Age': 18,'name':'Jin','Sex':'male'}dic.update (DIC1)#Add all key-value pairs in dic1 (same overlay, no add) to dic>>>{' Age': 18,'Sex':'Mans','Hobby':'Girl','Nero': 30,'name':'Jin'}dic['Key'] = value#If there is a change, there is no increase
Dictionary operation-Check
DIC = {' Age': 18,'name':'Jin','Sex':'male'}Print(Dict[key])#if the key is not in the dictionary, an error will beFor Loop lookupPrint(Dic.get ('Sex'))#if the key is not in the dictionary, none is returned, and the value of key is returned .>>>male
Python Learning Day5