查詢 Python 字典中的共同項
字典是 Python 中用於儲存資料的一種無序資料結構,它以鍵值對的形式儲存資料。在其他程式語言中,它也被稱為關聯陣列或雜湊對映。字典使用花括號{}表示,鍵和值之間用冒號“:”分隔。字典中的鍵是唯一的,而值可以是重複的。要訪問字典的元素,我們將使用鍵。
示例
以下是使用 Python 中可用的dic()方法和花括號{}建立字典的示例。
# creating dictionary using dict() method: l = [('name', 'John'), ('age', 25), ('city', 'New York')] dic = dict(l) print("The dictionary created using dict() method",dic) # creating dictionary using {}: dic = {'name' : 'John', 'age' : 25, 'city' :'New York'} print("The dictionary created using {}",dic)
輸出
The dictionary created using dict() method {'name': 'John', 'age': 25, 'city': 'New York'} The dictionary created using {} {'name': 'John', 'age': 25, 'city': 'New York'}
有多種方法可以查詢 Python 字典中的共同項。讓我們詳細瞭解每種方法。
使用集合交集
一種直接的方法是將字典的鍵轉換為集合,然後使用集合交集運算子&查詢共同的鍵。
示例
在這個示例中,我們首先使用set(dict1.keys())和set(dict2.keys())將dict1和dict2的鍵轉換為集合。然後,集合交集&運算子執行集合交集,得到一個包含共同鍵的集合。最後,我們透過遍歷共同鍵並從dict1中獲取相應的值來建立一個新的字典common_items。
dict1 = {'a': 1, 'b': 2, 'c': 3} dict2 = {'b': 20, 'c': 30, 'd': 40} common_keys = set(dict1.keys()) & set(dict2.keys()) common_items = {key: dict1[key] for key in common_keys} print("The common items in the dictionaries dict1,dict2:",common_items)
輸出
The common items in the dictionaries dict1,dict2: {'c': 3, 'b': 2}
使用字典推導式
這種方法是使用字典推導式,它可以直接建立一個僅包含共同鍵值對的新字典。
示例
在這種方法中,我們使用for key in dict1遍歷dict1的鍵,對於每個鍵,我們使用條件if key in dict2檢查它是否在dict2中存在。如果條件為真,我們將鍵值對包含在common_items字典中。
dict1 = {'a': 1, 'b': 2, 'c': 3} dict2 = {'b': 20, 'c': 30, 'd': 40} common_items = {key: dict1[key] for key in dict1 if key in dict2} print("The common items in the dictionaries dict1,dict2:",common_items)
輸出
The common items in the dictionaries dict1,dict2: {'b': 2, 'c': 3}
使用items()方法
items()方法返回一個包含字典鍵值對的檢視物件。我們可以使用此方法遍歷項並過濾出共同項。
示例
在這種方法中,我們使用items()方法透過for key, value in dict1.items()遍歷dict1的鍵值對。然後我們檢查鍵是否在dict2中存在,以及兩個字典中對應的值是否相同。如果滿足這些條件,我們將鍵值對包含在common_items字典中。
dict1 = {'a': 1, 'b': 2, 'c': 3} dict2 = {'b': 20, 'c': 30, 'd': 40} common_items = {key: value for key, value in dict1.items() if key in dict2 and dict2[key] == value} print("The common items in the dictionaries dict1,dict2:",common_items)
輸出
The common items in the dictionaries dict1,dict2: {}
廣告