This article mainly introduces the use of Python3 in Dict (dictionary), the text gives a detailed list of functions, for everyone has a certain reference value, the need for friends below to see it together.
One, clear (Empty dictionary contents)
Stu = { ' num1 ': ' Tom ', ' num2 ': ' Lucy ', ' num3 ': ' Sam ',}print (Stu.clear ()) #输出: None
Ii. Copy (copy dictionary)
Stu = { ' num1 ': ' Tom ', ' num2 ': ' Lucy ', ' num3 ': ' Sam ',}stu2 = Stu.copy () print (STU2)
Three, Fromkeys (Specify a list, the value in the list as the dictionary key, generate a dictionary)
name = [' Tom ', ' Lucy ', ' Sam ']print (Dict.fromkeys (name)) print (Dict.fromkeys (name,25)) #指定默认值 # output: {' tom ': None, ' Lucy ': None, ' Sam ': none}# {' tom ': +, ' Lucy ': +, ' Sam ': 25}
Four, get (specify key, get the corresponding value)
Stu = { ' num1 ': ' Tom ', ' num2 ': ' Lucy ', ' num3 ': ' Sam ',}print (Stu.get (' num2 ')) #输出: Lucy
V. Items (returns a list of elements that are composed of "key-value pairs")
Stu = { ' num1 ': ' Tom ', ' num2 ': ' Lucy ', ' num3 ': ' Sam ',}print (Stu.items ()) #输出: Dict_items ([(' Num2 ', ' Lucy ') , (' num3 ', ' Sam '), (' Num1 ', ' Tom ')]
Vi. keys (get all keys in the dictionary)
Stu = { ' num1 ': ' Tom ', ' num2 ': ' Lucy ', ' num3 ': ' Sam ',}print (Stu.keys ()) #输出: Dict_keys ([' num3 ', ' num1 ', ' Num2 '])
Seven, pop (gets the value of the specified key and is deleted in the dictionary)
Stu = { ' num1 ': ' Tom ', ' num2 ': ' Lucy ', ' num3 ': ' Sam ',}name = Stu.pop (' num2 ') print (name,stu) #输出: Lucy {' Num1 ': ' Tom ', ' num3 ': ' Sam '}
Eight, Popitem (random get a key value pair, and delete in the dictionary)
Stu = { ' num1 ': ' Tom ', ' num2 ': ' Lucy ', ' num3 ': ' Sam ',}name = Stu.popitem () print (Name,stu) #输出: (' num2 ', ' Lucy ') {' num3 ': ' Sam ', ' num1 ': ' Tom '}
IX, SetDefault (Gets the value of the specified key, if key does not exist, creates)
Stu = { ' num1 ': ' Tom ', ' num2 ': ' Lucy ', ' num3 ': ' Sam ',}name = Stu.setdefault (' NUM5 ') print (name,stu) # Output: None {' num1 ': ' Tom ', ' num2 ': ' Lucy ', ' num5 ': None, ' num3 ': ' Sam '}
X. Update (add key-value pairs to dictionary)
Stu = { ' num1 ': ' Tom ', ' num2 ': ' Lucy ', ' num3 ': ' Sam ',}stu.update ({' num4 ': ' Ben '}) print (stu) #输出: {' num2 ' : ' Lucy ', ' num3 ': ' Sam ', ' num1 ': ' Tom ', ' num4 ': ' Ben '}