dictionary
Dictionary (Dictionary) , a list similar to the dictionary may be stored a plurality of elements , this plurality of elements called object storage container (Container) .
And similar places dictionary table includes a plurality of elements , each element separated by commas.
However, the dictionary element comprises two parts, keys and values , based on common string represents a bond, may also be used to represent the true value or numeric key (immutable objects can be used as the key).
Value can be any object. Both keys and values correspond.
Unlike tables, the elements of the dictionary is not sequential . You can not subscript reference element. The dictionary is by key referenced.
1 # dictionary: {} 2 >>> DIC = { ' Tom ' :. 11, ' SAM ' : 57 is, ' Lily ' : 100} # dictionary usage, {} is the number, and the key value . 3 >>> Print type (DIC) # print dictionary type . 4 <type ' dict ' > . 5 >>> Print DIC [ ' tom ' ] # output value tom . 6 . 11 . 7 >>> DIC [ 'meng '] = 14 # add meng value . 8 >>> Print DIC . 9 { ' meng ' : 14, ' Lily ' : 100, ' SAM ' : 57 is, ' Tom ' :. 11 } 10 >>> DIC [ ' Tom ' ] = 30 # modified value tom . 11 >>> Print DIC 12 is { ' Meng ' : 14, ' Lily ' : 100,'SAM ' : 57 is, ' Tom ' : 30 }
14 # empty dictionary 15 >>> DIC = {} 16 >>> Print DIC . 17 {}
summary:
1. Note that the dictionary of basic usage, a {} numbers, and the key value.
2. The reference time for the DIC [ 'Tom' ] .
Cycle call dictionary
1 >>> dic = {'tom':11, 'sam':57,'lily':100} 2 >>> print key #输出报错 3 Traceback (most recent call last): 4 File "<pyshell#1>", line 1, in <module> 5 print key 6 NameError: name 'key' is not defined 7 >>> print value #输出报错 8 Traceback (most recent call last): 9 File "<pyshell#38>", line 1, in <module> 10 print value 11 NameError: name 'value' is not defined 12 13 >>> print dic['tom'] #输出tom的值 14 11 15 >>> for key in dic: 16 printKey # Key output value of the loop, there is no order . 17 Lily 18 is SAM . 19 Tom 20 is 21 is >>> for Key in DIC: # value output value of the loop, nor the order of 22 is Print DIC [Key] 23 is 100 24 57 is 25 . 11
In a loop, each key of dict, is extracted, assigned to key variables.
In the above example, the keys and values are not sequential.
Common method
. 1 >>> dim = { ' Tom ' :. 11, ' SAM ' : 57 is, ' Lily ' : 100 } 2 >>> Print dim.keys () # Returns all keys dim . 3 [ ' Lily ' , ' SAM ' , ' Tom ' ] . 4 >>> Print dim.values () # returns all the values Dim . 5 [100, 57 is,. 11 ] . 6 >>> Printdim.items () # Returns dim all key-value pairs . 7 [( ' Lily ' , 100), ( ' SAM ' , 57 is), ( ' Tom ' ,. 11 )] . 8 >>> Print (len (dim)) # Find the total number of elements dim . 9 . 3 10 >>> del dim [ ' tom ' ] # deleted tom values in dim . 11 >>> Print dim 12 is { ' Lily ' : 100,'SAM ' : 57 is } 13 is >>> dim.clear () # empty dim, dim} becomes { 14 >>> Print Dim 15 {}
del keyword Python reserved for deleting objects.