Python 中的字典操作

Python 中的字典操作

本文將介紹 Python 中的字典操作。

您可以通過實例代碼學習如何定義字典、基本操作、字典合併等內容。

YouTube Video

Python 中的字典操作

在 Python 中,字典(dict)是一種以鍵值對管理資料的集合。與列表不同,字典是以而非位置來存取,因此查詢與更新都很有效率。

字典的定義

1my_dict = {
2    'apple': 3,
3    'banana': 5,
4    'orange': 2
5}
6print(my_dict)
  • 字典使用大括號 {} 表示,鍵與值之間以冒號 : 分隔。

訪問鍵和值

1print(my_dict['apple'])  # Output: 3
  • 指定鍵即可取得對應的值。

向字典中添加或更新項目

1my_dict['pear'] = 4  # Add a new item
2my_dict['apple'] = 5  # Update an existing item
3print(my_dict)
  • 您可以添加新的鍵值對或更新現有鍵的值。

從字典中刪除項目

1del my_dict['banana']
2print(my_dict)
  • 使用 del 會刪除指定的鍵及其值。
1value = my_dict.pop('orange')  # Remove the item 'orange' and get its value
2print(value)
3print(my_dict)
  • 或者,使用 pop 方法刪除項目並檢索其值。

檢查字典中是否存在鍵

1if 'apple' in my_dict:
2    print("Apple is in the dictionary.")
  • 使用 in 運算子來測試鍵是否存在於字典中。

遍歷字典

1for key, value in my_dict.items():
2    print(f"{key}: {value}")
  • 使用 items() 方法遍歷字典,處理其鍵和值。items() 方法可同時迭代鍵與值。

僅檢索字典中的鍵或值

1keys = my_dict.keys()
2values = my_dict.values()
3print(keys)
4print(values)
  • 使用 keys() 方法僅檢索鍵,或使用 values() 方法僅檢索值。

複製字典

1new_dict = my_dict.copy()
2print(new_dict)
  • 使用 copy() 方法來創建字典的副本。copy() 方法會建立淺層複製。若要複製巢狀字典,可以使用 copy.deepcopy()

合併字典

1dict1 = {'apple': 3, 'banana': 5}
2dict2 = {'orange': 2, 'pear': 4}
3combined_dict = dict1 | dict2
4print(combined_dict)
  • 從 Python 3.9 開始,| 運算符可以作為合併字典的新方法。
1dict1.update(dict2)
2print(dict1)
  • 在舊版中,請使用 update() 方法。

總結

在 Python 程式設計中,字典是進行資料管理的基礎工具。它們以鍵值對管理資料,並具備許多優點,包括快速存取、彈性更新以及容易合併。熟練掌握字典的用法後,你將能寫出更高效率且更具彈性的程式碼。

您可以在我們的 YouTube 頻道上使用 Visual Studio Code 來跟隨上述文章一起學習。 請也查看我們的 YouTube 頻道。

YouTube Video