Python - Extract Dictionary Items with Summation Greater than K
Last Updated :
27 Apr, 2023
Given dictionary with value lists, extract all those items with values summing over K.
Input : {"Gfg" : [6, 3, 4], "is" : [8, 10, 12], "Best" : [10, 16, 14], "for" : [7, 4, 3], "geeks" : [1, 2, 3, 4]}, K = 10
Output : {"Gfg" : [6, 3, 4], "is" : [8, 10, 12], "Best" : [10, 16, 14], "for" : [7, 4, 3], "geeks" : [1, 2, 3, 4]}
Explanation : All elements are greater than 10.
Input : {"Gfg" : [6, 3, 4], "is" : [8, 10, 12], "Best" : [10, 16, 14], "for" : [7, 4, 3], "geeks" : [1, 2, 3, 4]}, K = 50
Output : {}
Explanation : No elements are greater than 50.
Method #1 : Using dictionary comprehension + sum()
This is one of the ways in which this problem can be solved. In this one-liner, we iterate through the keys and append the dictionary item only if its value's total crosses K computed using sum().
Python3
# Python3 code to demonstrate working of
# Extract Dictionary Items with Summation Greater than K
# Using dictionary comprehension + sum()
# initializing dictionary
test_dict = {"Gfg" : [6, 3, 4],
"is" : [8, 10, 12],
"Best" : [10, 16, 14],
"for" : [7, 4, 3],
"geeks" : [1, 2, 3, 4]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing K
K = 15
# summation using sum(), values extracted using items()
res = {key: val for key, val in test_dict.items() if sum(val) > K}
# printing result
print("The computed dictionary : " + str(res))
OutputThe original dictionary is : {'Gfg': [6, 3, 4], 'is': [8, 10, 12], 'Best': [10, 16, 14], 'for': [7, 4, 3], 'geeks': [1, 2, 3, 4]}
The computed dictionary : {'is': [8, 10, 12], 'Best': [10, 16, 14]}
Time Complexity: O(n), where n is the length of the list test_dict
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
Method #2 : Using filter() + lambda() + sum() + dict()
This is another way in which this task can be performed. In this, computation part is done using filter() and lambda, summation using sum() and result converted to dictionary using dict().
Python3
# Python3 code to demonstrate working of
# Extract Dictionary Items with Summation Greater than K
# Using filter() + lambda() + sum() + dict()
# initializing dictionary
test_dict = {"Gfg" : [6, 3, 4],
"is" : [8, 10, 12],
"Best" : [10, 16, 14],
"for" : [7, 4, 3],
"geeks" : [1, 2, 3, 4]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing K
K = 15
# summation using sum(), values extracted using items()
# filter() + lambda used for computation
res = dict(filter(lambda ele: sum(ele[1]) > K, test_dict.items()))
# printing result
print("The computed dictionary : " + str(res))
OutputThe original dictionary is : {'Gfg': [6, 3, 4], 'is': [8, 10, 12], 'Best': [10, 16, 14], 'for': [7, 4, 3], 'geeks': [1, 2, 3, 4]}
The computed dictionary : {'is': [8, 10, 12], 'Best': [10, 16, 14]}
Method #3: Using for loop and if statement
- Initialize the dictionary test_dict with the given key-value pairs.
- Print the original dictionary.
- Initialize the value of K.
- Create an empty dictionary res to store the computed dictionary.
- Loop through the key-value pairs in test_dict.
- For each key-value pair, compute the sum of the values using sum(value).
- Check if the sum is greater than K.
- If the sum is greater than K, add the key-value pair to res.
- Print the computed dictionary.
Python3
# initializing dictionary
test_dict = {"Gfg" : [6, 3, 4],
"is" : [8, 10, 12],
"Best" : [10, 16, 14],
"for" : [7, 4, 3],
"geeks" : [1, 2, 3, 4]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing K
K = 15
# initializing result dictionary
res = {}
# loop through the dictionary and check if the sum of the values is greater than K
for key, value in test_dict.items():
if sum(value) > K:
res[key] = value
# printing result
print("The computed dictionary : " + str(res))
OutputThe original dictionary is : {'Gfg': [6, 3, 4], 'is': [8, 10, 12], 'Best': [10, 16, 14], 'for': [7, 4, 3], 'geeks': [1, 2, 3, 4]}
The computed dictionary : {'is': [8, 10, 12], 'Best': [10, 16, 14]}
Time complexity: O(n), where n is the number of key-value pairs in the dictionary
Auxiliary space: O(k), where k is the number of key-value pairs in the result dictionary (in the worst case, all key-value pairs in the original dictionary satisfy the condition and are included in the result dictionary)
Method #4: Using the reduce() function from the functools module
Step-by-step approach:
Import the functools module.
Initialize the dictionary and K value as given in the problem statement.
Use the reduce() function to iterate through the dictionary and check if the sum of the values is greater than K. If yes, add the key-value pair to the resulting dictionary.
Print the resulting dictionary.
Python3
# import the functools module
import functools
# initializing dictionary
test_dict = {"Gfg" : [6, 3, 4],
"is" : [8, 10, 12],
"Best" : [10, 16, 14],
"for" : [7, 4, 3],
"geeks" : [1, 2, 3, 4]}
# initializing K
K = 15
# using reduce() to iterate through the dictionary and filter out key-value pairs whose sum of values is greater than K
res = functools.reduce(lambda acc, item: dict(list(acc.items()) + [(item, test_dict[item])]) if sum(test_dict[item]) > K else acc, test_dict.keys(), {})
# printing result
print("The computed dictionary : " + str(res))
OutputThe computed dictionary : {'is': [8, 10, 12], 'Best': [10, 16, 14]}
Time complexity: O(n), where n is the number of key-value pairs in the dictionary.
Auxiliary space: O(1) for the variables used in the code, and O(n) for the resulting dictionary
Similar Reads
Python - Extract dictionaries with values sum greater than K
Given a dictionaries list, extract all the dictionaries whose keys summation exceeds K. Input : test_list = [{"Gfg" : 4, "is" : 8, "best" : 9}, {"Gfg" : 3, "is": 7, "best" : 5}], K = 15 Output : [{'Gfg': 4, 'is': 8, 'best': 9}] Explanation : 4 + 9 + 8 = 21. Greater than K, hence returned. Input : te
8 min read
Python - Storing Elements Greater than K as Dictionary
Sometimes, while working with python lists, we can have a problem in which we need to extract elements greater than K. But sometimes, we don't require to store duplicacy and hence store by key value pair in dictionary. To track of number position of occurrence in dictionary. Method #1 : Using loop T
3 min read
Python - Extract element with relative difference greater than K
Given a list of numbers, the task is to write a Python program to extract all numbers with differences of the next and previous elements with a current greater than K. Input : test_list = [2, 7, 4, 1, 9, 2, 3, 10, 1, 5], K = 4Output : [9, 10]Explanation : 9 has 1 as preceding element and 2 as succee
4 min read
Python | Select dictionary with condition given key greater than k
In Python, sometimes we require to get only some of the dictionary required to solve the problem. This problem is quite common in web development that we require to get only the selective dictionary satisfying some given criteria. Letâs discuss certain ways in which this problem can be solved. Metho
3 min read
Python - Dictionary Keys whose Values summation equals K
Given a dictionary and a value K, extract keys whose summation of values equals K. Input : {"Gfg" : 3, "is" : 5, "Best" : 9, "for" : 8, "Geeks" : 10}, K = 17 Output : ['Best', 'for'] Explanation : 9 + 8 = 17, hence those keys are extracted. Input : {"Gfg" : 3, "is" : 5, "Best" : 9, "for" : 8, "Geeks
9 min read
Python - Extract dictionaries with Empty String value in K key
Given a List of dictionaries, extract all the dictionaries which have empty strings as values of a particular key. Input : test_list = [{"Gfg" : "4", "is" : "good", "best" : "1"}, {"Gfg" : "9", "is" : "CS", "best" : "10"}], K = "Gfg" Output : [] Explanation : No "Gfg" key is empty. Input : test_list
8 min read
Python - Test if Values Sum is Greater than Keys Sum in dictionary
Given a Dictionary, check if the summation of values is greater than the keys sum. Input : test_dict = {5:3, 1:3, 10:4, 7:3, 8:1, 9:5} Output : False Explanation : Values sum = 19 < 40, which is key sum, i.e false.Input : test_dict = {5:3, 1:4} Output : True Explanation : Values sum = 7 >
8 min read
Get first K items in dictionary = Python
We are given a dictionary and a number K, our task is to extract the first K key-value pairs. This can be useful when working with large dictionaries where only a subset of elements is needed. For example, if we have: d = {'a': 1, 'b': 2, 'c': 3, 'd': 4} and K = 2 then the expected output would be:
2 min read
Python | Extract specific keys from dictionary
We have a lot of variations and applications of dictionary containers in Python and sometimes, we wish to perform a filter of keys in a dictionary, i.e extracting just the keys which are present in the particular container. Let's discuss certain ways in which this can be performed. Extract specific
4 min read
Python - Nested Dictionary values summation
Sometimes, while working with Python dictionaries, we can have problem in which we have nested records and we need cumulative summation of it's keys values. This can have possible application in domains such as web development and competitive programming. Lets discuss certain ways in which this task
8 min read