dictionary
increase
1. Cover if there is, add if not
dic = { ' name ' : ' old boy ' , ' age ' : 56 , ' hobby ' : ' women ' } dic['sex'] = 'LaddyBoy' dic['name'] = 'Alex'
2. If there is, it will not change, if not, add it
dic = { ' name ' : ' old boy ' , ' age ' : 56, ' hobby ' : ' women ' } dic.setdefault('sex', 'Laddyboy') dic.setdefault('name', 'alex') print(dic)
delete
1. pop Delete according to Key, there is a return value, return the value of the corresponding key to delete.
dic = { ' name ' : ' old boy ' , ' age ' : 56, ' hobby ' : ' women ' } print (dic.pop( ' age ' )) print (dic.pop( ' age1 ' , ' without this Key... ' )) #If there is no error, but adding the value will return the value you wrote print (dic)
2. clear clears the dictionary
dic = { ' name ' : ' old boy ' , ' age ' : 56, ' hobby ' : ' women ' } dic.clear() print (Dec)
3. pop.item is deleted randomly, there is a return value, and the return is the ancestor, which is the deleted key pair value
dic = { ' name ' : ' old boy ' , ' age ' : 56, ' hobby ' : ' women ' } print (dic.popitem()) print (dic)
4. del deletes the entire dictionary
delete by key
dic = {'name': '老男孩', 'age': 56, 'hobby': 'women'} del dic['name'] print(dic)
change
1. dic['name'] = 'Alex' If there is, it will be overwritten and added if not
2. update update of two dictionaries
dic = {"name": "jin", "age": 18, "sex": "male"} dic2 = {"name": "alex", "weight": 75} dic2.update(dic) #Add all key-value pairs in dic to dic2, dic remains unchanged print (dic) # {'name': 'jin', 'age': 18, 'sex': 'male' '} print (dic2) # {'name': 'jin', 'weight': 75, 'age': 18, 'sex': 'male'}
check
1. If there is, return the value, no error is reported
# 1,dic['name'] dic = {'name': '老男孩', 'age': 56, 'hobby': 'women'} print(dic['name'])
2. If there is, return the value, if not return None
2,dic.get('name')
dic = { ' name ' : ' old boy ' , ' age ' : 56, ' hobby ' : ' women ' } print (dic.get( ' name ' )) print (dic.get( ' name1 ' )) print ( dic.get( ' name1 ' , ' sb does not have this key ' ))
3. for loop query
dic.keys(), dic.values(), dic.items() #Similar to list but not the type of list.
# cycle key
dic = {'name': '老男孩', 'age': 56, 'hobby': 'women'} for key in dic.keys(): print(key)
# loop value
dic = {'name': '老男孩', 'age': 56, 'hobby': 'women'} for value in dic.values(): print(value)
# Loop keys and values are assigned separately
dic = {'name': '老男孩', 'age': 56, 'hobby': 'women'} for k,v in dic.items(): print(k,v)