Python - 提取值之和大于 K 的字典


当需要提取值之和大于 K 的字典时,可以使用一个简单的迭代和“if”条件。

示例

以下是对此进行演示 -

Open Compiler
my_list = [{"Python" : 14, "is" : 18, "fun" : 19},{"Python" : 12, "is": 4, "fun" : 16}, {"Python" : 13, "is": 17, "fun" : 11},{"Python" : 13, "is": 16, "fun" : 13}] print("The list :") print(my_list) K =35 print("The value for K :") print(K) my_result = [] for index in my_list: sum = 0 for key in index: sum += index[key] if sum > K: my_result.append(index) print("The result is :") print(my_result)

输出

The list :
[{'Python': 14, 'is': 18, 'fun': 19}, {'Python': 12, 'is': 4, 'fun': 16}, {'Python': 13, 'is': 17, 'fun': 11}, {'Python': 13, 'is': 16, 'fun': 13}]
The value for K :
35
The result is :
[{'Python': 14, 'is': 18, 'fun': 19}, {'Python': 13, 'is': 17, 'fun': 11}, {'Python': 13, 'is': 16, 'fun': 13}]

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

说明

  • 定义了一个字典列表并将其显示在控制台上。

  • 定义了 K 的值并将其显示在控制台上。

  • 创建了一个空列表。

  • 迭代该列表,并将求和值初始化为 0。

  • 如果列表中存在特定的键,则将元素添加到求和中。

  • 如果求和大于‘K’,则将索引值附加到空列表中。

  • 此列表就是输出,显示在控制台上。

更新于: 2021 年 9 月 8 日

440 次浏览量

开启你的 职业生涯

通过完成课程获得认证

开始
广告