
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Extract Dictionaries with Values Sum Greater than K in Python
When it is required to extract dictionaries with values sum greater than K, a simple iteration and ‘if’ condition is used.
Example
Below is a demonstration of the same −
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)
Output
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}]
Explanation
A list of dictionary is defined and displayed on the console.
The value for K is defined and displayed on the console.
An empty list is created.
The list is iterated over, and a sum value is initialized to 0.
If the specific key is present the list, the element is added to the sum.
If the sum is greater than ‘K’, the index value is appended to the empty list.
This list is the output that is displayed on the console.
Advertisements