字典
python里的字典就像java里的HashMap,以鍵值對的方式存在並操作,其特點如下
- 通過鍵來存取,而非偏移量;
- 鍵值對是無序的;
- 鍵和值可以是任意對象;
- 長度可變,任意嵌套;
- 在字典里,不能再有序列操作,雖然字典在某些方面與列表類似,但不要把列表套在字典上。
-
1 #coding:utf-8 2 #!/usr/bin/python 3 # Filename: map.py 4 5 table = {'abc':1, 'def':2, 'ghi':3} 6 print table 7 8 #字典反轉 9 map=dict([(v,k) for k, v in table.iteritems()]) 10 #字典遍歷 11 for key in map.keys(): 12 print key,":",map[key] 13 14 print len(map) 15 print map.keys() 16 print map.values() 17 18 #字典的增,刪,改,查 19 #在這里需要來一句,對於字典的擴充,只需定義一個新的鍵值對即可, 20 #而對於列表,就只能用append方法或分片賦值。 21 map[4]="xyz" 22 print map 23 24 del map[4] 25 print map 26 27 map[3]="update" 28 print map 29 30 if map.has_key(1): 31 print "1 key in" 32 33 {'abc': 1, 'ghi': 3, 'def': 2} 34 1 : abc 35 2 : def 36 3 : ghi 37 3 38 [1, 2, 3] 39 ['abc', 'def', 'ghi'] 40 {1: 'abc', 2: 'def', 3: 'ghi', 4: 'xyz'} 41 {1: 'abc', 2: 'def', 3: 'ghi'} 42 {1: 'abc', 2: 'def', 3: 'update'} 43 1 key in