Python - 根据列表中第 K 个键的值过滤字典
pythonserver side programmingprogramming更新于 2025/10/29 7:08:17
当需要根据列表中第"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}]
解释
定义一个字典列表并显示在控制台上。
定义另一个整数列表和一个键。
定义一个空列表。
迭代列表,如果找到键,则将元素附加到表情列表中。
这是输出。
它显示在控制台上。
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

