字典是一個無序的集合,包含用逗號分隔的花括號內的key:value
對。 字典經過優化,可以在已知關鍵字的情況下檢索值。
下面聲明一個字典對象。
Example: Dictionary
capitals = {"USA":"Washington D.C.", "France":"Paris", "India":"New Delhi"}
上圖,capitals
是一個字典對象,其中包含{ }
內部的鍵值對。 左側:
為按鍵,右側為數值。 密鑰應該是唯一且不可變的對象。數字、字符串或元組可以用作關鍵字。因此,以下詞典也有效:
Example: Dictionary Objects
d = {} # empty dictionary
numNames={1:"One", 2: "Two", 3:"Three"} # int key, string value
decNames={1.5:"One and Half", 2.5: "Two and Half", 3.5:"Three and Half"} # float key, string value
items={("Parker","Reynolds","Camlin"):"pen", ("LG","Whirlpool","Samsung"): "Refrigerator"} # tuple key, string value
romanNums = {'I':1, 'II':2, 'III':3, 'IV':4, 'V':5} # string key, int value
但是,以列表作為關鍵字的字典是無效的,因為列表是可變的:
Error: List as Dict Key
dict_obj = {["Mango","Banana"]:"Fruit", ["Blue", "Red"]:"Color"}
但是,列表可以用作值。
Example: List as Dictionary Value
dict_obj = {"Fruit":["Mango","Banana"], "Color":["Blue", "Red"]}
同一個鍵在集合中不能出現多次。如果該密鑰出現多次,將只保留最后一次。該值可以是任何數據類型。一個值可以分配給多個鍵。
Example: Unique Keys
>>> numNames = {1:"One", 2:"Two", 3:"Three", 2:"Two", 1:"One"}
>>> numNames
{1:"One", 2:"Two", 3:"Three"}
dict
是所有字典的類,如下圖所示。
Example: Distinct Type
>>> numNames = {1:"One", 2:"Two", 3:"Three", 2:"Two", 1:"One"}
>>> type(numNames)
<class 'dict'>
也可以使用 dict() 構造器方法創建字典。
Example: dict() Constructor Method
>>> emptydict = dict()
>>> emptydict
{}
>>> numdict = dict(I='one', II='two', III='three')
>>> numdict
{'I': 'one', 'II': 'two', 'III': 'three'}
訪問字典
字典是一個無序的集合,因此不能使用索引訪問值;相反,必須在方括號中指定一個鍵,如下所示。
Example: Get Dictionary Values
>>> capitals = {"USA":"Washington DC", "France":"Paris", "India":"New Delhi"}
>>>capitals["USA"]
'Washington DC'
>>> capitals["France"]
'Paris'
>>> capitals["usa"] # Error: Key is case-sensitive
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
capitals['usa']
KeyError: 'usa'
>>> capitals["Japan"] # Error: key must exist
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
capitals['Japan']
KeyError: 'Japan'
*Note:*Keys are case-sensitive. So, usa
and USA
are treated as different keys. If the specified key does not exist then it will raise an error. *使用 get() 方法檢索鍵的值,即使鍵是未知的。 如果密鑰不存在,則返回None
,而不是產生錯誤。
Example: Get Dictionary Values
>>> capitals = {"USA":"Washington DC", "France":"Paris", "Japan":"Tokyo", "India":"New Delhi"}
>>> capitals.get("USA")
'Washington DC'
>>> capitals.get("France")
'Paris'
>>> capitals.get("usa")
>>> capitals.get("Japan")
>>>
使用 for
循環訪問字典
使用 for
循環迭代 Python 腳本中的字典。
Example: Access Dictionary Using For Loop
capitals = {"USA":"Washington D.C.", "France":"Paris", "India":"New Delhi"}
for key in capitals:
print("Key = " + key + ", Value = " + capitals[key])
Output
Key = 'USA', Value = 'Washington D.C.'
Key = 'France', Value = 'Paris'
Key = 'India', Value = 'New Delhi'
更新詞典
如前所述,密鑰不能出現多次。使用相同的鍵并為其分配新值,以更新字典對象。
Example: Update Value of Key
>>> captains = {"England":"Root", "Australia":"Smith", "India":"Dhoni"}
>>> captains['India'] = 'Virat'
>>> captains['Australia'] = 'Paine'
>>> captains
{'England': 'Root', 'Australia': 'Paine', 'India': 'Virat'}
使用新的鍵并為其賦值。字典將在其中顯示一個額外的鍵值對。
Example: Add New Key-Value Pair
>>> captains['SouthAfrica']='Plessis'
>>> captains
{'England': 'Root', 'Australia': 'Paine', 'India': 'Virat', 'SouthAfrica': 'Plessis'}
從字典中刪除值
使用 del 關鍵字、 pop() 或 popitem() 方法從字典或字典對象本身中刪除一對。要刪除一對,請使用其鍵作為參數。 要刪除字典對象,請使用其名稱。
Example: Delete Key-Value
>>> captains = {'England': 'Root', 'Australia': 'Paine', 'India': 'Virat', 'Srilanka': 'Jayasurya'}
>>> del captains['Srilanka'] # deletes a key-value pair
>>> captains
{'England': 'Root', 'Australia': 'Paine', 'India': 'Virat'}
>>> del captains # delete dict object
>>> captains
NameError: name 'captains' is not defined
NameError
表示字典對象已經從內存中移除。
檢索字典鍵和值
鍵()和值()方法分別返回包含鍵和值的視圖對象。
Example: keys()
>>> d1 = {'name': 'Steve', 'age': 21, 'marks': 60, 'course': 'Computer Engg'}
>>> d1.keys()
dict_keys(['name', 'age', 'marks', 'course'])
>>> d1.values()
dict_values(['Steve', 21, 60, 'Computer Engg'])
檢查字典鍵
您可以使用in
或not in
關鍵字檢查字典集合中是否存在主鍵,如下所示。 注意,它只檢查鍵,不檢查值。
Example: Check Keys
>>> captains = {'England': 'Root', 'Australia': 'Paine', 'India': 'Virat', 'Srilanka': 'Jayasurya'}
>>> 'England' in captains
True
>>> 'India' in captains
True
>>> 'France' in captains
False
>>> 'USA' not in captains
True
多維詞典
讓我們假設有三個字典對象,如下所示:
Example: Dictionary
>>> d1={"name":"Steve","age":25, "marks":60}
>>> d2={"name":"Anil","age":23, "marks":75}
>>> d3={"name":"Asha", "age":20, "marks":70}
讓我們給這些學生分配卷號,創建一個以卷號為關鍵字的多維字典,并根據它們的值對上述字典進行排序。
Example: Multi-dimensional Dictionary
>>> students={1:d1, 2:d2, 3:d3}
>>> students
{1: {'name': 'Steve', 'age': 25, 'marks': 60}, 2: {'name': 'Anil', 'age': 23, 'marks': 75}, 3: {'name': 'Asha', 'age': 20, 'marks': 70}}<
student
對象是一個二維字典。這里d1
、d2
和d3
分別被指定為鍵 1、2 和 3 的值。students[1]
返回d1
。
Example: Access Multi-dimensional Dictionary
>>> students[1]
{'name': 'Steve', 'age': 25, 'marks': 60}
>>> students[1]['age']
25
內置字典方法
方法 | 描述 |
---|---|
dict.clear() | 從字典中移除所有鍵值對。 |
dict.copy() | 返回字典的一個簡單副本。 |
發布 fromkeys() | 從給定的可迭代表(字符串、列表、集合、元組)創建一個新的字典作為鍵,并使用指定的值。 |
dict.get() | 返回指定鍵的值。 |
dict.items() | 返回字典視圖對象,該對象以鍵值對列表的形式提供字典元素的動態視圖。當字典改變時,這個視圖對象也隨之改變。 |
dict . key() | 返回包含字典鍵列表的字典視圖對象。 |
dict.pop() | 移除鍵并返回其值。如果字典中不存在某個鍵,則返回默認值(如果指定的話),否則將引發鍵錯誤。 |
關閉。潑皮() | 從字典中移除并返回(鍵、值)對的元組。成對按后進先出(后進先出)順序返回。 |
dict.setdefault() | 返回字典中指定鍵的值。如果找不到該鍵,則添加具有指定 defaultvalue 的鍵。如果未指定默認值,則設置為無值。 |
dict.update() | 使用來自另一個字典或另一個表(如具有鍵值對的元組)的鍵值對更新字典。 |
字典值() | 返回字典視圖對象,該對象提供字典中所有值的動態視圖。當字典 改變時,這個視圖對象改變。 |