data type - dictionary

 

Dictionary: a key-value data type, just like the dictionary we used in school, we can check the details of the corresponding page through strokes and letters.

characteristic:

  key-value structure

  The key must be hashable, must be an immutable data type, and must be unique

  Can store any number of values, can be modified, can not be unique

  disorder

  Find fast

grammar:

   info = {'a': 1, 'b': 2, 'c': 3} 

Increase:

   info[ ' chris ' ] = ' primary student ' 

Revise:

   info[ ' a ' ] = ' social person ' 

 

#Save/fetch 
info_dic={'name':'egon','age':18,'sex':'male'}
# print(info_dic['name11111111'])#If it cannot be found, an error will be reported
print(info_dic. get('name',None))
print(info_dic.get('name222222',None))#get method can't find no error, you can set the default value
by yourself info_dic.pop('age') #delete and return the value
info_dic.popitem() #Randomly delete
del info_dic['name'] #delete key
info_dic={ ' name ' : ' egon ' , ' age ' :18, ' sex ' : ' male ' }
 print (info_dic.keys()) #print all keys 
print (info_dic.values()) #print all value (value) 
print (info_dic.items()) #Generate   list #Print 
key and value 
for key in info_dic: #Quick    lookup print 
    ( key,info_dic[key])
 for k,v in info_dic.items():#this is slower 
    print (k,v)
 #length print (len(info_dic))
 print ( ' name ' in info_dic)
 print ( ' name ' in info_dic.keys())
 print ( ' egon ' in info_dic.values( ))
 print (( ' name ' , ' egon ' ) in info_dic.items())
   

#Master info_dic.update 
({ ' a ' :1, ' name ' : ' Egon ' })   #If not, add it, if there is, overwrite 
print (info_dic)

info_dic[ ' hobbies ' ]=[]   #Add a new key value, the value is an empty list 
info_dic[ ' hobbies ' ].append( ' study ' ) #Add study to the value of hobbies 
info_dic[ ' hobbies ' ].append ( ' read ' )
 print (info_dic)

# setdefault: if the key does not exist, set the default value and return the default value. 
# If the key exists, do not set the default and return the existing value 
print (info_dic.setdefault( ' name ' ,[1,2 ]))
 print ( info_dic.setdefault( ' hobbies ' ,[1,2,3,4,5 ]))
 print (info_dic)

#了解
d=info_dic.fromkeys(('name','age','sex'),None)
print(d)
d2=dict.fromkeys(('name','age','sex'),'keys')
print(d2)

info=dict(name='haiyan',age=18,sex='male')
print(info)


info=dict([('name','haiyan'),('age',18)])
print(info)

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324757954&siteId=291194637