Python Day 1-getting started with common operations on the Python (4) dictionary, python Day 1
1 # dic = {[123, 3]: '000000'} # variable types cannot be used as Dictionary keys. value can be of any type 2 # dic = {(, 4 ): '000000'} 3 # print (dic [(123, 4)]) # The Key 4 # dic = {1: 'A', 1: 'B'} 5 # print (dic [(1)]) # duplicate keys can be defined but the value of the last key is always taken.
1 # dic = {1: 'A', 2: 'B', 3: 'C'} # view key value 2 # print (dic [2]) 3 # dic = {1: 'A', 2: 'B', 3: 'C'} 4 # print (dic) 5 # dic [1] = 'chares _ Lee '# modify key value 6 # print (dic) 7 8 # dic = {1: 'A', 2:' B ', 3: 'C'} # delete key 9 # del dic [1] 10 # print (dic) 11 12 # dic = {1: 'A', 2: 'B ', 3: 'C'} 13 # dic ['key'] = 'value' # Add key value 14 # print (dic) 15 16 17 # dic = {1: 'A', 2: 'B', 3: 'C'} 18 # for I in dic: 19 # print (I) # traversing the key value 20 # print (I, dic [I]) # traversing the kye: value in the list
1 # dic = {1: 'A', 2: 'B', 3: 'C'} 2 # dic1 = {9: 'X', 8: 'y ', 7: 'Z', 1: 'A'} 3 # dic. update (dic1) 4 # print (dic) # Use dec1 to update some of dic to overwrite; if not, add it to dic 5 6 # dic = {1: 'A', 2: 'B', 3: 'C'} 7 # dic. setdefault ('sex', 'female ') # Set the default value, similar to dic ['sex'] = 'female '8 # print (dic) 9 10 # dic = {1: 'A', 2: 'B', 3: 'C'} 11 # dic. setdefault ('hobby', []). append ('read') # similar to dic ['hobby']. append ('read') 12 # print (dic)
1 # dic = {1: 'A', 2: 'B', 3: 'C'} 2 # dic. pop (1) # pop delete 3 # print (dic) 4 # dic = {1: 'A', 2: 'B', 3: 'C'} 5 # print (dic. pop ('dalsj ',' the deleted value cannot be found ') # Set the default value. If the pop value does not exist, no error is reported.
1 dic = {1: 'A', 2: 'B', 3: 'C'} 2 dic. clear () # clear dictionary 3 print (dic)
1 # dic = {1: 'A', 2: 'B', 3: 'C'} 2 # print (dic. popitem () 3 # print (dic) # Delete the kye: value in the dictionary randomly and return a tuple