
- Python 設計模式教程
- Python 設計模式 - 首頁
- 簡介
- Python 設計模式 - 要點
- 模型檢視控制器模式
- Python 設計模式 - 單例
- Python 設計模式 - 工廠
- Python 設計模式 - 構建器
- Python 設計模式 - 原型
- Python 設計模式 - 外觀
- Python 設計模式 - 命令
- Python 設計模式 - 介面卡
- Python 設計模式 - 裝飾器
- Python 設計模式 - 代理
- 責任鏈模式
- Python 設計模式 - 觀察者
- Python 設計模式 - 狀態
- Python 設計模式 - 策略
- Python 設計模式 - 模板
- Python 設計模式 - 輕量級
- 抽象工廠
- 面向物件
- 面向物件概念實現
- Python 設計模式 - 迭代器
- 字典
- 列表資料結構
- Python 設計模式 - 集合
- Python 設計模式 - 佇列
- 字串和序列化
- Python 中的併發
- Python 設計模式 - 反模式
- 異常處理
- Python 設計模式資源
- 快速指南
- Python 設計模式 - 資源
- 討論
Python 設計模式 - 字典
字典是資料結構,包括鍵值組合。它們廣泛用於替代 JSON(JavaScript 物件表示法)。字典用於 API(應用程式程式設計介面)程式設計。字典將一組物件對映到另一組物件。字典是可變的,這意味著可以根據需要隨時更改它們。
如何在 Python 中實現字典?
以下程式展示了在 Python 中實現字典的基本過程,從建立到實現。
# Create a new dictionary d = dict() # or d = {} # Add a key - value pairs to dictionary d['xyz'] = 123 d['abc'] = 345 # print the whole dictionary print(d) # print only the keys print(d.keys()) # print only values print(d.values()) # iterate over dictionary for i in d : print("%s %d" %(i, d[i])) # another method of iteration for index, value in enumerate(d): print (index, value , d[value]) # check if key exist 23. Python Data Structure –print('xyz' in d) # delete the key-value pair del d['xyz'] # check again print("xyz" in d)
輸出
上述程式生成以下輸出 −

注意 −在 Python 中實現字典存在缺點。
缺點
字典不支援諸如字串、元組和列表一類的序列資料型別的序列操作。這些屬於內建對映型別。
廣告