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("名单是:")
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("结果是:")
print(my_result)输出结果名单是:
[{'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}]
结果是:
[{'Python': 2, 'is': 4, 'cool': 11}, {'Python': 5, 'is': 1, 'cool': 1}, {'Python': 9, 'is': 9, 'cool': 8}]解释
一个字典列表被定义并显示在控制台上。
定义了另一个整数列表和一个键。
定义了一个空列表。
该列表被迭代,如果找到了键,则将该元素附加到emoty列表中。
这是输出。
它显示在控制台上。