definition (the key of the dictionary must be an immutable type, also become a hash type, and the dictionary is unordered): info={'name':'Egon',' Age': 18,'Sex':'male'} or Info=dict ({'name':'Egon',' Age': 18,'Sex':'male'})#take the value of a keyPrint(info[' Age'])#add key and valueinfo['Height']=1.80Print(Info)#Traverse Dictionary Key forKeyinchInfo:Print(key) Info={'name':'Egon',' Age': 18,'Sex':'male'}#eject the value of the specific key#Print (Info.pop (' name '))#Eject if you do not have this key, set the default valuePrint(Info.pop ('ASDFSADFASDFASFASDFASDFASDF', None))Print(info['name1'])Print(Info.get ('name1'))Print(Info.get ('NAMEASDFASDFASDFASDF','Not key'))#get a pair of key values and form a tupleinfo={'name':'Egon',' Age': 18,'Sex':'male'}Print(Info.popitem ())Print(Info.popitem ())Print(Info)##get all keys and values for the word yellowPrint(Info.keys (), type (Info.keys ()))Print(Info.values ())#get all key,values and form a tuple listPrint(Info.items ()) forKey,valueinchInfo.items ():#key,value= (' name ', ' Egon ') Print(Key,value)#Empty Dictionaryinfo={'name':'Egon',' Age': 18,'Sex':'male'}info.clear ()Print(Info)#quickly use Fromkeys to assign a value to the keys to generate a dictionaryPrint(Info.items ()) DiC=info.fromkeys (['name',' Age','Sex'],11111111)Print(DIC)#quickly generate a dictionary with dictDic=dict (a=1,b=2,c=3)Print(DIC)Print(Dict ([('name','Egon'), (' Age', 18), ('Sex','male')]))#update another dictionary with one dictionary, if the elements in the dictionary to be updated are not in the updated dictionary, fill indic={'a': 1,'b': 2,'name':'Shuai'}info.update (DIC)Print(Info)#add default value to a dictionary key there is no change, no then fill inD=dict.setdefault (['a','b','C'],[])Print(d) d={}Print(d) d['name']='Egon'd[' Age']=18d['Sex']='male'D.setdefault ('Hobby', []). Append ('Play1')#d[' hobby ']D.setdefault ('Hobby', []). Append ('Play2')#d[' hobby ']D.setdefault ('Hobby', []). Append ('Play3')#d[' hobby ']Print(d)
Definitions of Python dictionaries and common methods