Open In App

Python – Dictionary items in value range

Last Updated : 22 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a range of values, extract all the items whose keys lie in a range of values.

Input : {‘Gfg’ : 6, ‘is’ : 7, ‘best’ : 9, ‘for’ : 8, ‘geeks’ : 11}, i, j = 9, 12
Output : {‘best’ : 9, ‘geeks’ : 11} 
Explanation : Keys within 9 and 11 range extracted. 

Input : {‘Gfg’ : 6, ‘is’ : 7, ‘best’ : 9, ‘for’ : 8, ‘geeks’ : 11}, i, j = 14, 18 
Output : {} 
Explanation : No values in range.

Method #1: Using loop 

This is brute way in which this task can be performed. In this, we run a loop for all the keys with conditional checks for range of values.  

Python3




# Python3 code to demonstrate working of
# Dictionary items in value range
# Using loop
 
# initializing dictionary
test_dict = {'Gfg' : 6, 'is' : 7, 'best' : 9, 'for' : 8, 'geeks' : 11}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing range
i, j = 8, 12
 
# using loop to iterate through all keys
res = dict()
for key, val in test_dict.items():
    if int(val) >= i and int(val) <= j:
        res[key] = val
 
# printing result
print("The extracted dictionary : " + str(res))


Output

The original dictionary is : {'Gfg': 6, 'is': 7, 'best': 9, 'for': 8, 'geeks': 11}
The extracted dictionary : {'best': 9, 'for': 8, 'geeks': 11}

Time complexity: O(n), where n is the number of items in the dictionary. The for loop performs the range check on each item in the dictionary, which takes O(1) time, and the overall time complexity is O(n).
Auxiliary Space: O(m), where m is the number of items in the filtered dictionary. The filtered items are stored in a new dictionary (res), so the space complexity is proportional to the size of the filtered dictionary.

Method #2 : Using filter() + lambda + dictionary comprehension 

The combination of above functions can be used to solve this problem. In this, we perform task of filtering using filter() and lambda is used for conditional checks.

Python3




# Python3 code to demonstrate working of
# Dictionary items in value range
# Using filter() + lambda + dictionary comprehension
 
# initializing dictionary
test_dict = {'Gfg' : 6, 'is' : 7, 'best' : 9, 'for' : 8, 'geeks' : 11}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing range
i, j = 8, 12
 
# using dictionary comprehension to compile result in one
res = {key: val for key, val in filter(lambda sub: int(sub[1]) >= i and
                                   int(sub[1]) <= j, test_dict.items())}
 
# printing result
print("The extracted dictionary : " + str(res))


Output

The original dictionary is : {'Gfg': 6, 'is': 7, 'best': 9, 'for': 8, 'geeks': 11}
The extracted dictionary : {'best': 9, 'for': 8, 'geeks': 11}

Time complexity: O(n), where n is the number of items in the original dictionary.
Auxiliary space: O(k).

Method #3 : Using range(),keys() methods

Python3




# Python3 code to demonstrate working of
# Dictionary items in value range
# Using loop
 
# initializing dictionary
test_dict = {'Gfg' : 6, 'is' : 7, 'best' : 9, 'for' : 8, 'geeks' : 11}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing range
i, j = 8, 12
 
# using loop to iterate through all keys
res = dict()
x=[k for k in range(i,j)]
for i in list(test_dict.keys()):
    if(test_dict[i] in x):
        res[i]=test_dict[i]
# printing result
print("The extracted dictionary : " + str(res))


Output

The original dictionary is : {'Gfg': 6, 'is': 7, 'best': 9, 'for': 8, 'geeks': 11}
The extracted dictionary : {'best': 9, 'for': 8, 'geeks': 11}

Time Complexity : O(N)
Auxiliary Space : O(N)

Method 4: Using list comprehension and dict() constructor:

Python3




# initializing dictionary
test_dict = {'Gfg': 6, 'is': 7, 'best': 9, 'for': 8, 'geeks': 11}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing range
i, j = 8, 12
 
 
res = dict([(key, val) for key, val in test_dict.items() if i <= val <= j])
 
 
# printing the result
print("The extracted dictionary : " + str(res))


Output

The original dictionary is : {'Gfg': 6, 'is': 7, 'best': 9, 'for': 8, 'geeks': 11}
The extracted dictionary : {'best': 9, 'for': 8, 'geeks': 11}

Time Complexity: O(N)
Auxiliary Space: O(N)

Method #5: Using dictionary comprehension with conditionals

Use a dictionary comprehension with a conditional statement to filter items from the original dictionary that fall within the specified range. The resulting dictionary is assigned to the variable res, which is printed to the console.

Python3




# initializing dictionary
test_dict = {'Gfg' : 6, 'is' : 7, 'best' : 9, 'for' : 8, 'geeks' : 11}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing range
i, j = 8, 12
 
# using dictionary comprehension with conditionals to extract items
res = {key: val for key, val in test_dict.items() if i <= val <= j}
 
# printing result
print("The extracted dictionary : " + str(res))


Output

The original dictionary is : {'Gfg': 6, 'is': 7, 'best': 9, 'for': 8, 'geeks': 11}
The extracted dictionary : {'best': 9, 'for': 8, 'geeks': 11}

Time Complexity: O(N)
Auxiliary Space: O(N)

Method #6: Using the items() method and list comprehension

 using the items() method and a list comprehension. The input dictionary is first initialized, and then the range is set. The list comprehension is then used to iterate over each key-value pair in the dictionary, and only the pairs where the value falls within the specified range are added to the resulting dictionary. Finally, the resulting dictionary is printed to the console.

Initialize the input dictionary.
Set the range of values to extract from the dictionary.
Use the items() method to iterate over each key-value pair in the dictionary.
Within the iteration, use a list comprehension to check whether the value falls within the specified range.
If the value falls within the specified range, add the key-value pair to the resulting dictionary.
Once all key-value pairs have been checked, the resulting dictionary will contain only the key-value pairs where the value falls within the specified range.
Print the resulting dictionary to the console.

Python3




# initializing dictionary
test_dict = {'Gfg': 6, 'is': 7, 'best': 9, 'for': 8, 'geeks': 11}
 
# initializing range
i, j = 8, 12
 
# using the items() method and list comprehension to extract the required dictionary
res = {key: val for key, val in test_dict.items() if val in range(i, j+1)}
 
# printing result
print("The extracted dictionary : " + str(res))


Output

The extracted dictionary : {'best': 9, 'for': 8, 'geeks': 11}

time complexity of this method is O(n), where n is the number of items in the input dictionary, since we are iterating over all items in the dictionary. The auxiliary space complexity is also O(k), where k is the number of items in the resulting dictionary, since we are creating a new dictionary to store the extracted key-value pairs.

Method#7: Using Recursive method.

Algorithm:

  1. Define a recursive function, extract_dict_within_range, that takes three parameters: the input dictionary test_dict, and
  2. the lower and upper bounds of the range i and j, respectively.
  3. Check for the base case:
  4. If test_dict is empty or i is greater than j, return an empty dictionary.
  5. Initialize an empty dictionary, extracted_dict, to store the extracted items within the given range.
  6. Iterate through the key-value pairs of test_dict using a for loop.
  7. For each key-value pair, check if the value val is within the range [i, j] using val in range(i, j+1).
  8. If the value is within the range, add the key-value pair to extracted_dict.
  9. If the value is a nested dictionary, recursively call extract_dict_within_range on that nested dictionary with the same range [i, j], and update the value in extracted_dict with the result.
  10. After iterating through all the key-value pairs in test_dict, return extracted_dict.

Python3




def extract_dict_within_range(test_dict, i, j):
    # Base case: when the dictionary is empty or the range is invalid
    if not test_dict or i > j:
        return {}
     
    # Extract items within the given range
    extracted_dict = {key: val for key, val in test_dict.items() if val in range(i, j+1)}
     
    # Recursively call the function on the extracted items' values to get nested dictionaries
    for key, val in extracted_dict.items():
        if isinstance(val, dict):
            extracted_dict[key] = extract_dict_within_range(val, i, j)
     
    return extracted_dict
 
test_dict = {'Gfg': 6, 'is': 7, 'best': 9, 'for': 8, 'geeks': 11, 'nested_dict': {'a': 10, 'b': 12}}
i, j = 8, 12
res = extract_dict_within_range(test_dict, i, j)
print("The extracted dictionary : " + str(res))


Output

The extracted dictionary : {'best': 9, 'for': 8, 'geeks': 11}

The time complexity of the recursive method depends on the size and structure of the input dictionary test_dict, as well as the range [i, j]. In the worst case, where all items in test_dict need to be checked and all values are nested dictionaries, the time complexity would be O(NM), where N is the total number of key-value pairs in test_dict, and M is the maximum depth of nested dictionaries. 

The correct space complexity for the given recursive method is O(N), where N is the total number of key-value pairs in the input dictionary test_dict.



Previous Article
Next Article

Similar Reads

Python | Count number of items in a dictionary value that is a list
In Python, dictionary is a collection which is unordered, changeable and indexed. Dictionaries are written with curly brackets, and they have keys and values. It is used to hash a particular key. A dictionary has multiple key:value pairs. There can be multiple pairs where value corresponding to a key is a list. To check that the value is a list or
5 min read
Python - Common items Dictionary Value List
The functionality of union has been discussed many times. But sometimes, we can have a more complex container, in which we need to check for the intersection of lists which are in form of keys of dictionary. Let’s discuss certain ways to solve this type of problem. Method #1: Using Loops Using loops is a naive brute force approach to perform this p
10 min read
Python - Remove K value items from dictionary nesting
Given dictionary with multiple nestings, remove all the keys with value K. Input : [{"Gfg" : {"a" : 5, "b" : 8, "c" : 9}}, {"is" : {"j" : 8, "k" : 10}}, {"Best" : {"i" : 16}}], K = 8 Output : [{'a': 5}, {'c': 9}, {'k': 10}, {'i': 16}] Explanation : All the keys with value 8, ("b", "j") has been removed. Input : [{"Gfg" : {"a" : 5, "b" : 8, "c" : 9}
4 min read
Python Program to find the profit or loss when CP of N items is equal to SP of M items
Given [Tex]N   [/Tex]and [Tex]M   [/Tex]denoting that the Cost Price of N articles is equal to the Selling Price of M articles. The task is to determine the profit or Loss percentage. Examples:  Input: N = 8, M = 9 Output: Loss = -11.11% Input: N = 8, M = 5 Output: Profit = 60% Formula:-  Below is the implementation of the above approach: C/C++ Cod
1 min read
Convert Dictionary Value list to Dictionary List Python
Sometimes, while working with Python Dictionaries, we can have a problem in which we need to convert dictionary list to nested records dictionary taking each index of dictionary list value and flattening it. This kind of problem can have application in many domains. Let's discuss certain ways in which this task can be performed. Input : test_list =
9 min read
Python - Replace dictionary value from other dictionary
Given two dictionaries, update the values from other dictionary if key is present in other dictionary. Input : test_dict = {"Gfg" : 5, "is" : 8, "Best" : 10, "for" : 8, "Geeks" : 9}, updict = {"Geeks" : 10, "Best" : 17} Output : {'Gfg': 5, 'is': 8, 'Best': 17, 'for': 8, 'Geeks': 10} Explanation : "Geeks" and "Best" values updated to 10 and 17. Inpu
6 min read
Python - Combine two dictionaries having key of the first dictionary and value of the second dictionary
Given two dictionaries. The task is to merge them in such a way that the resulting dictionary contains the key from the first dictionary and the value from the second dictionary. Examples: Input : test_dict1 = {"Gfg" : 20, "is" : 36, "best" : 100}, test_dict2 = {"Gfg2" : 26, "is2" : 20, "best2" : 70} Output : {'Gfg': 26, 'is': 20, 'best': 70} Expla
8 min read
Python | Pretty Print a dictionary with dictionary value
This article provides a quick way to pretty How to Print Dictionary in Python that has a dictionary as values. This is required many times nowadays with the advent of NoSQL databases. Let's code a way to perform this particular task in Python. Example Input:{'gfg': {'remark': 'good', 'rate': 5}, 'cs': {'rate': 3}} Output: gfg: remark: good rate: 5
7 min read
Python Dictionary items() method
Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key : value pair.In Python Dictionary, items() method is used to return the list with all dictionary keys with values. Syntax: dictionary.items()Parameters: T
2 min read
Python program to find the sum of all items in a dictionary
Given a dictionary in Python, write a Python program to find the sum of all items in the dictionary. Examples: Input : {'a': 100, 'b':200, 'c':300}Output : 600 Input : {'x': 25, 'y':18, 'z':45}Output : 88 Method #1: Using Inbuilt sum() Function Use the sum function to find the sum of dictionary values. C/C++ Code # Python3 Program to find sum of #
6 min read
Practice Tags :