[转]python 之字典{}(Hashmap)

字典

  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
原文地址:https://www.cnblogs.com/xrhou12326/p/3400224.html