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