用法:
class dict(**kwargs)class dict(mapping, **kwargs)class dict(iterable, **kwargs)返回一個從可選位置參數和一組可能為空的關鍵字參數初始化的新字典。
可以通過多種方式創建字典:
- 在大括號內使用逗號分隔的
key: value對列表:{'jack': 4098, 'sjoerd': 4127}或{4098: 'jack', 4127: 'sjoerd'} - 使用字典理解:
{},{x: x ** 2 for x in range(10)} - 使用類型構造函數:
dict(),dict([('foo', 100), ('bar', 200)]),dict(foo=100, bar=200)
如果沒有給出位置參數,則創建一個空字典。如果給定位置參數並且它是映射對象,則使用與映射對象相同的鍵值對創建字典。否則,位置參數必須是可迭代對象。可迭代對象中的每個項目本身必須是恰好具有兩個對象的可迭代對象。每個項目的第一個對象成為新字典中的鍵,第二個對象成為相應的值。如果一個鍵出現多次,則該鍵的最後一個值將成為新字典中的對應值。
如果給出了關鍵字參數,則將關鍵字參數及其值添加到從位置參數創建的字典中。如果要添加的鍵已經存在,則關鍵字參數的值將替換位置參數的值。
為了說明,以下示例都返回一個等於
{"one": 1, "two": 2, "three": 3}的字典:>>> a = dict(one=1, two=2, three=3) >>> b = {'one': 1, 'two': 2, 'three': 3} >>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3])) >>> d = dict([('two', 2), ('one', 1), ('three', 3)]) >>> e = dict({'three': 3, 'one': 1, 'two': 2}) >>> f = dict({'one': 1, 'three': 3}, two=2) >>> a == b == c == d == e == f True在第一個示例中提供關鍵字參數僅適用於作為有效 Python 標識符的鍵。否則,可以使用任何有效的 key 。
這些是字典支持的操作(因此,自定義映射類型也應該支持):
-
list(d) 返回字典
d中使用的所有鍵的列表。
-
len(d) 返回字典
d中的項目數。
-
d[key] 使用鍵
key返回d的項目。如果key不在Map中,則引發KeyError。如果 dict 的子類定義了方法
__missing__()並且key不存在,則d[key]操作使用鍵key作為參數調用該方法。然後d[key]操作返回或引發__missing__(key)調用返回或引發的任何內容。沒有其他操作或方法調用__missing__()。如果未定義__missing__(),則會引發KeyError。__missing__()必須是方法;它不能是實例變量:>>> class Counter(dict): ... def __missing__(self, key): ... return 0 >>> c = Counter() >>> c['red'] 0 >>> c['red'] += 1 >>> c['red'] 1上麵的示例顯示了
collections.Counter的部分實現。collections.defaultdict使用了不同的__missing__方法。
-
d[key] = value 將
d[key]設置為value。
-
del d[key] 從
d中刪除d[key]。如果key不在Map中,則引發KeyError。
-
key in d 如果
d有鍵key,則返回True,否則返回False。
-
key not in d 等效於
not key in d。
-
iter(d) 返回字典鍵的迭代器。這是
iter(d.keys())的快捷方式。
-
reversed(d) 在字典的鍵上返回一個反向迭代器。這是
reversed(d.keys())的快捷方式。3.8 版中的新函數。
-
d | other 使用合並的
d和other的鍵和值創建一個新字典,它們必須都是字典。當d和other共享 key 時,other的值優先。3.9 版中的新函數。
-
d |= other 使用來自
other的鍵和值更新字典d,這可能是鍵/值對的映射或迭代。當d和other共享 key 時,other的值優先。3.9 版中的新函數。
字典比較相等當且僅當它們具有相同的
(key, value)對(無論順序如何)。訂單比較('='、'>')引發TypeError。字典保留插入順序。請注意,更新 key 不會影響順序。刪除後添加的鍵插入到最後。
>>> d = {"one": 1, "two": 2, "three": 3, "four": 4} >>> d {'one': 1, 'two': 2, 'three': 3, 'four': 4} >>> list(d) ['one', 'two', 'three', 'four'] >>> list(d.values()) [1, 2, 3, 4] >>> d["one"] = 42 >>> d {'one': 42, 'two': 2, 'three': 3, 'four': 4} >>> del d["two"] >>> d["two"] = None >>> d {'one': 42, 'three': 3, 'four': 4, 'two': None}在 3.7 版中更改:字典順序保證為插入順序。這種行為是 CPython 3.6 的實現細節。
字典和字典視圖是可逆的。
>>> d = {"one": 1, "two": 2, "three": 3, "four": 4} >>> d {'one': 1, 'two': 2, 'three': 3, 'four': 4} >>> list(reversed(d)) ['four', 'three', 'two', 'one'] >>> list(reversed(d.values())) [4, 3, 2, 1] >>> list(reversed(d.items())) [('four', 4), ('three', 3), ('two', 2), ('one', 1)]在 3.8 版中更改:字典現在是可逆的。
- 在大括號內使用逗號分隔的
相關用法
- Python dict()用法及代碼示例
- Python dictionary update()用法及代碼示例
- Python dictionary values()用法及代碼示例
- Python dictionary type()用法及代碼示例
- Python dictionary fromkeys()用法及代碼示例
- Python dictionary cmp()用法及代碼示例
- Python dictionary get()用法及代碼示例
- Python dict.values用法及代碼示例
- Python dictionary setdefault()用法及代碼示例
- Python distributed.protocol.serialize.register_generic用法及代碼示例
- Python distributed.Client.gather用法及代碼示例
- Python distributed.recreate_tasks.ReplayTaskClient.recreate_task_locally用法及代碼示例
- Python distributed.diagnostics.plugin.SchedulerPlugin用法及代碼示例
- Python distributed.Client.ncores用法及代碼示例
- Python distributed.Client.retire_workers用法及代碼示例
- Python distributed.Client.unregister_worker_plugin用法及代碼示例
- Python distributed.fire_and_forget用法及代碼示例
- Python dir用法及代碼示例
- Python distributed.Client.set_metadata用法及代碼示例
- Python distributed.Client.scheduler_info用法及代碼示例
注:本文由純淨天空篩選整理自python.org大神的英文原創作品 dict。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
