Python - 按照列表的第 K 個鍵中的值篩選詞典
當需要按照列表中“第 K”個鍵中的值篩選詞典時,將使用簡單的迭代並指定條件。
示例
以下是相同內容的演示
my_list = [{"Python": 2, "is": 4, "cool": 11},
{"Python": 5, "is": 1, "cool": 1},
{"Python": 7, "is": 3, "cool": 7},
{"Python": 9, "is": 9, "cool": 8},
{"Python": 4, "is": 10, "cool": 6}]
print("The list is :")
print(my_list)
search_list = [1, 9, 8, 4, 5]
key = "is"
my_result = []
for sub in my_list:
if sub[key] in search_list:
my_result.append(sub)
print("The result is :")
print(my_result)輸出
The list is :
[{'Python': 2, 'is': 4, 'cool': 11}, {'Python': 5, 'is': 1, 'cool': 1}, {'Python': 7, 'is': 3, 'cool': 7}, {'Python': 9, 'is': 9, 'cool': 8}, {'Python': 4, 'is': 10, 'cool': 6}]
The result is :
[{'Python': 2, 'is': 4, 'cool': 11}, {'Python': 5, 'is': 1, 'cool': 1}, {'Python': 9, 'is': 9, 'cool': 8}]說明
定義了一個詞典列表,並在控制檯上顯示出來。
定義了另一個整數列表和金鑰。
定義了一個空列表。
迭代列表,如果找到該鍵,則將該元素追加到空列表。
這是輸出。
它顯示在控制檯上。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP