字典(Dictionary)

在 python 中有一種集合為 dictionary (字典),能儲存成對的key(鍵值)&value(相對應的數)。
以日常生活舉例,key就像是車站旁保險箱的鑰匙,value就是箱子內的物品,而全部的保險箱就是一個Dictionary;每一個key值都會有一個相對應的value。

  • 建立一個空白的字典
D1 = {}
  • 顯示字典
print D1
  • 顯示字典長度
print "Length = ", len(D1)
  • 增加新的 key 與其相對應的 value
D1['0'] = 'zero' 
D1['1'] = 'one' 
D1['2'] = 'two' 
D1['3'] = 'three' 
D1['4'] = 'four'
  • 然後再來看一段簡單示範的程式碼
d = {'a' : 123 , 'b' : 456}
d2 = d.copy()  #複製d
print d
 
print 'a' in d   #傳回d裡面是否有'a'此key值
print d['a']     #印出'a'的value
print len(d)    #印出d的長度
 
d['c'] = 789    #插入'c'
print len(d)     #顯示插入後的長度
print d.has_key('c')   #回傳d裡面是否有'c'此key值
print d
 
print d.keys()  #印出包含所有key值的List
print d.values() #印出包含所有value值的List
print d.items() #印出包含所有(key,value)之Tuple的List
 
z = iter(d.itervalues())
print z.next()
#--------result-------------
{'a': 123, 'b': 456}
True
123
2
3
True
{'a': 123, 'c': 789, 'b': 456}
['a', 'c', 'b']
[123, 789, 456]
[('a', 123), ('c', 789), ('b', 456)]
123
  • 活用範例 - 動態新增:

以下適用於當我們不確定或是希望增加不定數量的參數時所使用

>>>class doSomething:
        def Todo(self,**va):
            self.__dict__.update((va))
 
>>>test = sum()
>>>test.Todo(x = 10 , y = "test" , z = True)
 
#測試結果
 
>>>test.x
10
>>>test.y
'test'
>>>test.z
True
 
#測試類型
 
>>>type(test.x)
<type 'int'>
>>>type(test.y)
<type 'str'>
>>>type(test.z)
<type 'bool'>