字典簡介
字典是鍵值儲存的示例,也稱為 Python 中的對映。它允許你通過引用鍵來儲存和檢索元素。由於字典是由金鑰引用的,因此它們具有非常快速的查詢。由於它們主要用於按鍵引用專案,因此它們不會被排序。
創造一個字典
字典可以通過多種方式啟動:
文字語法
d = {} # empty dict
d = {'key': 'value'} # dict with initial values
Python 3.x >= 3.5
# Also unpacking one or multiple dictionaries with the literal syntax is possible
# makes a shallow copy of otherdict
d = {**otherdict}
# also updates the shallow copy with the contents of the yetanotherdict.
d = {**otherdict, **yetanotherdict}
dict 理解
d = {k:v for k,v in [('key', 'value',)]}
另見: 理解
內建類:dict()
d = dict() # emtpy dict
d = dict(key='value') # explicit keyword arguments
d = dict([('key', 'value')]) # passing in a list of key/value pairs
# make a shallow copy of another dict (only possible if keys are only strings!)
d = dict(**otherdict)
修改字典
要將項新增到字典,只需建立一個帶有值的新鍵:
d['newkey'] = 42
也可以新增 list
和 dictionary
作為值:
d['new_list'] = [1, 2, 3]
d['new_dict'] = {'nested_dict': 1}
要刪除專案,請從字典中刪除金鑰:
del d['newkey']