
- Python 基礎
- Python - 首頁
- Python - 概述
- Python - 歷史
- Python - 特性
- Python vs C++
- Python - Hello World 程式
- Python - 應用領域
- Python - 直譯器
- Python - 環境搭建
- Python - 虛擬環境
- Python - 基本語法
- Python - 變數
- Python - 資料型別
- Python - 型別轉換
- Python - Unicode 系統
- Python - 字面量
- Python - 運算子
- Python - 算術運算子
- Python - 比較運算子
- Python - 賦值運算子
- Python - 邏輯運算子
- Python - 位運算子
- Python - 成員運算子
- Python - 身份運算子
- Python - 運算子優先順序
- Python - 註釋
- Python - 使用者輸入
- Python - 數字
- Python - 布林值
- Python 控制語句
- Python - 控制流
- Python - 決策
- Python - if 語句
- Python - if else
- Python - 巢狀 if
- Python - match-case 語句
- Python - 迴圈
- Python - for 迴圈
- Python - for-else 迴圈
- Python - while 迴圈
- Python - break 語句
- Python - continue 語句
- Python - pass 語句
- 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 - 訪問列表元素
- 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 - 迴圈遍歷集合
- 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 - 反轉陣列
- Python - 排序陣列
- Python - 合併陣列
- Python - 陣列方法
- Python - 陣列練習
- Python 檔案處理
- Python - 檔案處理
- Python - 寫入檔案
- Python - 讀取檔案
- Python - 重新命名和刪除檔案
- Python - 目錄
- Python - 檔案方法
- Python - OS 檔案/目錄方法
- Python - OS 路徑方法
- 面向物件程式設計
- Python - OOPs 概念
- 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 - 異常
- Python - try-except 塊
- Python - try-finally 塊
- Python - 丟擲異常
- Python - 異常鏈
- Python - 巢狀 try 塊
- 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 - URL 處理
- Python - 泛型
- Python 庫
- NumPy 教程
- Pandas 教程
- SciPy 教程
- Matplotlib 教程
- Django 教程
- OpenCV 教程
- Python 雜項
- Python - 日期 & 時間
- Python - 數學
- Python - 迭代器
- Python - 生成器
- Python - 閉包
- Python - 裝飾器
- Python - 遞迴
- Python - 正則表示式
- Python - PIP
- Python - 資料庫訪問
- Python - 弱引用
- Python - 序列化
- Python - 模板
- Python - 輸出格式化
- Python - 效能測量
- Python - 資料壓縮
- Python - CGI 程式設計
- Python - XML 處理
- Python - GUI 程式設計
- Python - 命令列引數
- Python - 文件字串
- Python - JSON
- Python - 傳送郵件
- Python - 擴充套件
- Python - 工具/實用程式
- Python - GUI
- Python 高階概念
- Python - 抽象基類
- Python - 自定義異常
- Python - 高階函式
- Python - 物件內部
- Python - 記憶體管理
- Python - 元類
- Python - 使用元類進行超程式設計
- Python - 模擬和存根
- Python - 猴子補丁
- Python - 訊號處理
- Python - 型別提示
- Python - 自動化教程
- Python - Humanize 包
- Python - 上下文管理器
- Python - 協程
- Python - 描述符
- Python - 診斷和修復記憶體洩漏
- Python - 不可變資料結構
- Python 有用資源
- Python - 問答
- Python - 線上測驗
- Python - 快速指南
- Python - 參考
- Python - 速查表
- Python - 專案
- Python - 有用資源
- Python - 討論
- Python 編譯器
- NumPy 編譯器
- Matplotlib 編譯器
- SciPy 編譯器
Python - 字典
Python 中的字典
在 Python 中,字典是一種內建資料型別,用於以鍵值對的形式儲存資料。它是一個無序的、可變的、索引的集合。字典中的每個鍵都是唯一的,並且對映到一個值。字典通常用於儲存相關的資料,例如與特定實體或物件相關的資訊,您可以在其中根據其鍵快速檢索值。
Python 的字典是對映型別的示例。對映物件將一個物件的 value 對映到另一個物件。為了在鍵和值之間建立對映,冒號 (:) 符號放在兩者之間。
每個鍵值對由逗號分隔,並用花括號 {} 括起來。每個對中的鍵和值由冒號 (:) 分隔,形成 key:value 的結構。
以下是一些 Python 字典物件的示例 -
capitals = {"Maharashtra":"Mumbai", "Gujarat":"Gandhinagar", "Telangana":"Hyderabad", "Karnataka":"Bengaluru"} numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"} marks = {"Savita":67, "Imtiaz":88, "Laxman":91, "David":49}
字典的關鍵特性
以下是字典的關鍵特性 -
無序 - 字典中的元素沒有特定的順序。3.7 版本之前的 Python 字典不維護插入順序。從 Python 3.7 開始,字典作為語言特性維護插入順序。
可變 - 在建立字典之後,可以更改、新增或刪除項。
索引 - 儘管字典沒有數字索引,但它們使用鍵作為索引來訪問關聯的值。
唯一鍵 - 字典中的每個鍵都必須是唯一的。如果嘗試將值分配給現有鍵,則舊值將被新值替換。
異構 - 字典中的鍵和值可以是任何資料型別。
示例 1
只有數字、字串或元組可以用作鍵。它們都是不可變的。您可以使用任何型別的物件作為值。因此,以下字典定義也有效 -
d1 = {"Fruit":["Mango","Banana"], "Flower":["Rose", "Lotus"]} d2 = {('India, USA'):'Countries', ('New Delhi', 'New York'):'Capitals'} print (d1) print (d2)
它將產生以下輸出 -
{'Fruit': ['Mango', 'Banana'], 'Flower': ['Rose', 'Lotus']} {'India, USA': 'Countries', ('New Delhi', 'New York'): 'Capitals'}
示例 2
Python 不接受列表等可變物件作為鍵,並引發 TypeError。
d1 = {["Mango","Banana"]:"Fruit", "Flower":["Rose", "Lotus"]} print (d1)
它將引發 TypeError -
Traceback (most recent call last): File "C:\Users\Sairam\PycharmProjects\pythonProject\main.py", line 8, in <module> d1 = {["Mango","Banana"]:"Fruit", "Flower":["Rose", "Lotus"]} ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: unhashable type: 'list'
示例 3
您可以將值分配給字典中的多個鍵,但一個鍵不能在字典中出現多次。
d1 = {"Banana":"Fruit", "Rose":"Flower", "Lotus":"Flower", "Mango":"Fruit"} d2 = {"Fruit":"Banana","Flower":"Rose", "Fruit":"Mango", "Flower":"Lotus"} print (d1) print (d2)
它將產生以下輸出 -
{'Banana': 'Fruit', 'Rose': 'Flower', 'Lotus': 'Flower', 'Mango': 'Fruit'} {'Fruit': 'Mango', 'Flower': 'Lotus'}
建立字典
在 Python 中,您可以透過在花括號 {} 內放置用逗號分隔的鍵值對序列來建立字典,其中用冒號 : 分隔每個鍵及其關聯的值。或者,您可以使用 dict() 函式。
示例
以下示例演示瞭如何使用花括號和 dict() 函式建立名為“student_info”的字典 -
# Creating a dictionary using curly braces sports_player = { "Name": "Sachin Tendulkar", "Age": 48, "Sport": "Cricket" } print ("Dictionary using curly braces:", sports_player) # Creating a dictionary using the dict() function student_info = dict(name="Alice", age=21, major="Computer Science") print("Dictionary using dict():",student_info)
產生的結果如下所示 -
Dictionary using curly braces: {'Name': 'Sachin Tendulkar', 'Age': 48, 'Sport': 'Cricket'} Dictionary using dict(): {'name': 'Alice', 'age': 21, 'major': 'Computer Science'}
訪問字典項
您可以使用方括號 [] 或 get() 方法訪問與特定鍵關聯的值 -
student_info = { "name": "Alice", "age": 21, "major": "Computer Science" } # Accessing values using square brackets name = student_info["name"] print("Name:",name) # Accessing values using the get() method age = student_info.get("age") print("Age:",age)
獲得的結果如下 -
Name: Alice Age: 21
修改字典項
您可以修改與特定鍵關聯的值或新增新的鍵值對 -student_info = { "name": "Alice", "age": 21, "major": "Computer Science" } # Modifying an existing key-value pair student_info["age"] = 22 # Adding a new key-value pair student_info["graduation_year"] = 2023 print("The modified dictionary is:",student_info)
以上程式碼的輸出如下 -
The modified dictionary is: {'name': 'Alice', 'age': 22, 'major': 'Computer Science', 'graduation_year': 2023}
刪除字典項
您可以使用 del 語句、pop() 方法或 popitem() 方法刪除項 -
student_info = { "name": "Alice", "age": 22, "major": "Computer Science", "graduation_year": 2023 } # Removing an item using the del statement del student_info["major"] # Removing an item using the pop() method graduation_year = student_info.pop("graduation_year") print(student_info)
以下是以上程式碼的輸出 -
{'name': 'Alice', 'age': 22}
遍歷字典
您可以使用迴圈遍歷字典中的鍵、值或鍵值對 -
student_info = { "name": "Alice", "age": 22, "major": "Computer Science", "graduation_year": 2023 } # Iterating through keys for key in student_info: print("Keys:",key, student_info[key]) # Iterating through values for value in student_info.values(): print("Values:",value) # Iterating through key-value pairs for key, value in student_info.items(): print("Key:Value:",key, value)
執行以上程式碼後,我們將獲得以下輸出 -
Keys: name Alice Keys: age 22 Keys: major Computer Science Keys: graduation_year 2023 Values: Alice Values: 22 Values: Computer Science Values: 2023 Key:Value: name Alice Key:Value: age 22 Key:Value: major Computer Science Key:Value: graduation_year 2023
字典鍵的屬性
字典值沒有任何限制。它們可以是任何任意 Python 物件,無論是標準物件還是使用者定義的物件。但是,鍵的情況並非如此。
關於字典鍵,有兩點需要注意 -
- 每個鍵只能有一個條目。這意味著不允許重複鍵。當在賦值過程中遇到重複鍵時,最後一次賦值將生效。例如 -
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'} print ("dict['Name']: ", dict['Name'])
執行以上程式碼時,會產生以下結果 -
dict['Name']: Manni
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: unhashable type: 'list'
Python 字典運算子
在 Python 中,定義了以下運算子用於字典運算元。在示例中,使用了以下字典物件。
d1 = {'a': 2, 'b': 4, 'c': 30} d2 = {'a1': 20, 'b1': 40, 'c1': 60}
運算子 | 描述 | 示例 |
---|---|---|
dict[key] | 提取/分配與鍵對映的值 | print (d1['b']) 檢索 4 d1['b'] = 'Z' 將新值分配給鍵 'b' |
dict1|dict2 | 兩個字典物件的並集,返回新物件 | d3=d1|d2 ; print (d3) {'a': 2, 'b': 4, 'c': 30, 'a1': 20, 'b1': 40, 'c1': 60} |
dict1|=dict2 | 增強的字典並集運算子 | d1|=d2; print (d1) {'a': 2, 'b': 4, 'c': 30, 'a1': 20, 'b1': 40, 'c1': 60} |
Python 字典方法
Python 包含以下字典方法 -
序號 | 方法及描述 |
---|---|
1 | dict.clear()
刪除字典 dict 的所有元素 |
2 | dict.copy()
返回字典 dict 的淺複製 |
3 | dict.fromkeys()
建立一個新的字典,其鍵來自 seq,值設定為 value。 |
4 | dict.get(key, default=None)
對於key 鍵,返回 value 或 default(如果鍵不在字典中) |
5 | dict.has_key(key)
如果鍵在字典 dict 中,則返回 true,否則返回 false |
6 | dict.items()
返回 dict 的 (鍵,值) 元組對列表 |
7 | dict.keys()
返回字典 dict 的鍵列表 |
8 | dict.setdefault(key, default=None)
類似於 get(),但如果key 不在 dict 中,則會設定 dict[key]=default |
9 | dict.update(dict2)
將字典 dict2 的鍵值對新增到 dict |
10 | dict.values()
返回字典 dict 的值列表 |
與字典一起使用的內建函式
以下是我們可以與字典一起使用的內建函式 -
序號 | 函式及描述 |
---|---|
1 | cmp(dict1, dict2)
比較兩個 dict 的元素。 |
2 | len(dict)
給出字典的總長度。這將等於字典中專案的數量。 |
3 | str(dict)
生成字典的可列印字串表示形式 |
4 | type(variable)
返回傳遞變數的型別。如果傳遞的變數是字典,則它將返回字典型別。 |