# Python?字典(Dictionary)
字典是另一種可變容器模型,且可存儲任意類型對象,如其他容器模型。
字典由鍵和對應值成對組成。字典也被稱作關聯數組或哈希表。基本語法如下:
~~~
dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
~~~
也可如此創建字典:
~~~
dict1 = { 'abc': 456 };
dict2 = { 'abc': 123, 98.6: 37 };
~~~
每個鍵與值用冒號隔開(:),每對用逗號分割,整體放在花括號中({})。
鍵必須獨一無二,但值則不必。
值可以取任何數據類型,但必須是不可變的,如字符串,數或元組。
## 訪問字典里的值
把相應的鍵放入熟悉的方括弧,如下實例:
~~~
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
print "dict['Name']: ", dict['Name'];
print "dict['Age']: ", dict['Age'];
~~~
以上實例輸出結果:
~~~
dict['Name']: Zara
dict['Age']: 7
~~~
如果用字典里沒有的鍵訪問數據,會輸出錯誤如下:
~~~
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
print "dict['Alice']: ", dict['Alice'];
~~~
以上實例輸出結果:
~~~
dict['Zara']:
Traceback (most recent call last):
File "test.py", line 4, in <module>
print "dict['Alice']: ", dict['Alice'];
KeyError: 'Alice'
~~~
## 修改字典
向字典添加新內容的方法是增加新的鍵/值對,修改或刪除已有鍵/值對如下實例:
~~~
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry
print "dict['Age']: ", dict['Age'];
print "dict['School']: ", dict['School'];
~~~
以上實例輸出結果:
~~~
dict['Age']: 8
dict['School']: DPS School
~~~
## 刪除字典元素
能刪單一的元素也能清空字典,清空只需一項操作。
顯示刪除一個字典用del命令,如下實例:
~~~
#!/usr/bin/python
# -*- coding: UTF-8 -*-
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
del dict['Name']; # 刪除鍵是'Name'的條目
dict.clear(); # 清空詞典所有條目
del dict ; # 刪除詞典
print "dict['Age']: ", dict['Age'];
print "dict['School']: ", dict['School'];
~~~
但這會引發一個異常,因為用del后字典不再存在:
~~~
dict['Age']:
Traceback (most recent call last):
File "test.py", line 8, in <module>
print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable
~~~
注:del()方法后面也會討論。
## 刪除字典元素
字典鍵的特性
字典值可以沒有限制地取任何python對象,既可以是標準的對象,也可以是用戶定義的,但鍵不行。
兩個重要的點需要記住:
1)不允許同一個鍵出現兩次。創建時如果同一個鍵被賦值兩次,后一個值會被記住,如下實例:
~~~
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'};
print "dict['Name']: ", dict['Name'];
~~~
以上實例輸出結果:
~~~
dict['Name']: Manni
~~~
2)鍵必須不可變,所以可以用數,字符串或元組充當,所以用列表就不行,如下實例:
~~~
#!/usr/bin/python
dict = {['Name']: 'Zara', 'Age': 7};
print "dict['Name']: ", dict['Name'];
~~~
以上實例輸出結果:
~~~
Traceback (most recent call last):
File "test.py", line 3, in <module>
dict = {['Name']: 'Zara', 'Age': 7};
TypeError: list objects are unhashable
~~~
## 字典內置函數&方法
Python字典包含了以下內置函數:
| 序號 | 函數及描述 |
|--|--|
| 1 | [cmp(dict1, dict2)](http://www.runoob.com/python/att-dictionary-cmp.html)比較兩個字典元素。 |
| 2 | [len(dict)](http://www.runoob.com/python/att-dictionary-len.html)計算字典元素個數,即鍵的總數。 |
| 3 | [str(dict)](http://www.runoob.com/python/att-dictionary-str.html)輸出字典可打印的字符串表示。 |
| 4 | [type(variable)](http://www.runoob.com/python/att-dictionary-type.html)返回輸入的變量類型,如果變量是字典就返回字典類型。 |
Python字典包含了以下內置函數:
| 序號 | 函數及描述 |
|--|--|
| 1 | [radiansdict.clear()](http://www.runoob.com/python/att-dictionary-clear.html)刪除字典內所有元素 |
| 2 | [radiansdict.copy()](http://www.runoob.com/python/att-dictionary-copy.html)返回一個字典的淺復制 |
| 3 | [radiansdict.fromkeys()](http://www.runoob.com/python/att-dictionary-fromkeys.html)創建一個新字典,以序列seq中元素做字典的鍵,val為字典所有鍵對應的初始值 |
| 4 | [radiansdict.get(key, default=None)](http://www.runoob.com/python/att-dictionary-get.html)返回指定鍵的值,如果值不在字典中返回default值 |
| 5 | [radiansdict.has_key(key)](http://www.runoob.com/python/att-dictionary-has_key.html)如果鍵在字典dict里返回true,否則返回false |
| 6 | [radiansdict.items()](http://www.runoob.com/python/att-dictionary-items.html)以列表返回可遍歷的(鍵, 值) 元組數組 |
| 7 | [radiansdict.keys()](http://www.runoob.com/python/att-dictionary-keys.html)以列表返回一個字典所有的鍵 |
| 8 | [radiansdict.setdefault(key, default=None)](http://www.runoob.com/python/att-dictionary-setdefault.html)和get()類似, 但如果鍵不已經存在于字典中,將會添加鍵并將值設為default |
| 9 | [radiansdict.update(dict2)](http://www.runoob.com/python/att-dictionary-update.html)把字典dict2的鍵/值對更新到dict里 |
| 10 | [radiansdict.values()](http://www.runoob.com/python/att-dictionary-values.html)以列表返回字典中的所有值 |