Python - 根據特定列表中的值過濾字典鍵
我們在編寫 Python 字典時,有時需要根據特定條件來篩選出字典中的某些鍵。本文將介紹如何從 Python 字典中篩選出鍵。
使用 for 和 in
採用這種方法時,我們會將要篩選的鍵的值放入一個列表中。然後遍歷列表中的每個元素,並檢查它是否存在於給定的字典中。我們建立一個結果字典,其中包含在字典中找到的這些值。
示例
dictA= {'Mon':'Phy','Tue':'chem','Wed':'Math','Thu':'Bio'}
key_list = ['Tue','Thu']
print("Given Dictionary:\n",dictA)
print("Keys for filter:\n",key_list)
res = [dictA[i] for i in key_list if i in dictA]
print("Dictionary with filtered keys:\n",res)輸出
執行以上程式碼會得到以下結果 −
Given Dictionary:
{'Mon': 'Phy', 'Tue': 'chem', 'Wed': 'Math', 'Thu': 'Bio'}
Keys for filter:
['Tue', 'Thu']
Dictionary with filtered keys:
['chem', 'Bio']使用交集
我們使用交集來找到給定字典和列表之間的公共元素。然後應用 set 函式來獲取不同的元素,並將結果轉換為列表。
示例
dictA= {'Mon':'Phy','Tue':'chem','Wed':'Math','Thu':'Bio'}
key_list = ['Tue','Thu']
print("Given Dictionary:\n",dictA)
print("Keys for filter:\n",key_list)
temp = list(set(key_list).intersection(dictA))
res = [dictA[i] for i in temp]
print("Dictionary with filtered keys:\n",res)輸出
執行以上程式碼會得到以下結果 −
Given Dictionary:
{'Mon': 'Phy', 'Tue': 'chem', 'Wed': 'Math', 'Thu': 'Bio'}
Keys for filter:
['Tue', 'Thu']
Dictionary with filtered keys:
['chem', 'Bio']
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP