The Wayback Machine - https://web.archive.org/web/20241107134706/https://www.geeksforgeeks.org/python-dictionary-items-in-value-range/
Open In App

Python – Dictionary items in value range

Last Updated : 22 Apr, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 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
Python | Delete items from dictionary while iterating
A dictionary in Python is an ordered collection of data values. Unlike other Data Types that hold only a single value as an element, a dictionary holds the key: value pairs. Dictionary keys must be unique and must be of an immutable data type such as a: string, integer or tuple. Note: In Python 2 dictionary keys were unordered. As of Python 3, they
3 min read
Python | Get items in sorted order from given dictionary
Given a dictionary, the task is to get all items from the dictionary in sorted order. Let's discuss different ways we can do this task. Method #1: Using sorted() C/C++ Code # Python code to demonstrate # to get sorted items from dictionary # initialising _dictionary ini_dict = {'a': 'akshat', 'b': 'bhuvan', 'c': 'chandan'} # printing iniial_diction
3 min read
Python | Get first K items in dictionary
While working with dictionaries, we can come across a problem in which we might have to get just some of the initial keys in dictionary. This problem can typically occur in cases of the web development domain. Let's discuss certain ways in which this problem can be solved. Method #1 : Using items() + list slicing To solve this problem, a combinatio
6 min read
Python | Type conversion of dictionary items
The interconversion of data types is quite common, and we may have this problem while working with dictionaries as well. We might have a key and corresponding list with numeric alphabets, and we with to transform the whole dictionary to integers rather than string numerics. Let's discuss certain ways in which this task can be performed. Method #1 :
6 min read
Python | Sort the items alphabetically from given dictionary
Given a dictionary, write a Python program to get the alphabetically sorted items from given dictionary and print it. Let’s see some ways we can do this task. Code #1: Using dict.items() C/C++ Code # Python program to sort the items alphabetically from given dictionary # initialising _dictionary dict = {'key2' : 'For', 'key3': 'IsGeeks', 'key1' : '
1 min read
Python - Frequency of unequal items in Dictionary
Sometimes, while working with Python, we can come across a problem in which we need to check for the unequal items count among two dictionaries. This has an application in cases of web development and other domains as well. Let’s discuss certain ways in which this task can be performed. Method #1: Using dictionary comprehension This particular task
5 min read
Python - All possible items combination dictionary
Sometimes, while working with data, we can have a problem in which we are provided with sample data of key and value list and we require to construct actual data as all possible combination of keys and value list of similar size. Lets discuss certain ways in which this task can be performed. Method #1 : Using loop + set() The combination of above f
4 min read
Python - Sorted order Dictionary items pairing
Sometimes, while working with Python dictionaries, we can have problem in which we need to perform reordering of dictionary items, to pair key and values in sorted order, smallest pairing to smallest value, largest to largest value and so on. This kind of application can occur in competitive domain and day-day programming. Lets discuss certain ways
3 min read
Python - Assign list items to Dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to assign list elements as a new key in dictionary. This task can occur in web development domain. Lets discuss certain ways in which this task can be performed. Method #1 : Using zip() + loop The combination of above functions can be used to solve this proble
10 min read
Python - Extract dictionary items with List elements
Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract all the items from dictionary that constitute all the elements from a list. This kind of problem can occur in domains such as competitive programming and web development. Let's discuss certain ways in which this task can be performed. Input : test_d
8 min read
Python - Convert dictionary items to values
Sometimes, while working with Python dictionary, we can have a problem in which we need to convert all the items of dictionary to a separate value dictionary. This problem can occur in applications in which we receive dictionary in which both keys and values need to be mapped as separate values. Let's discuss certain ways in which this task can be
3 min read
Python program to convert URL Parameters to Dictionary items
Given URL Parameters string, convert to dictionary items. Input : test_str = 'gfg=4&is=5' Output : {'gfg': ['4'], 'is': ['5']} Explanation : gfg's value is 4. Input : test_str = 'gfg=4' Output : {'gfg': ['4']} Explanation : gfg's value is 4 as param. Method #1 : Using urllib.parse.parse_qs() This is default inbuilt function which performs this
5 min read
Python - Column Mapped Tuples to dictionary items
Given Tuple Matrix of length 2, map each column's element value with next column and construct dictionary keys. Input : test_list = [[(1, 4), (6, 3), (4, 7)], [(7, 3), (10, 14), (11, 22)]] Output : {1: 7, 4: 3, 6: 10, 3: 14, 4: 11, 7: 22} Explanation : 1 -> 7, 4 -> 3.., as in same column and indices. Input : test_list = [[(1, 4), (6, 3)], [(7
4 min read
Python - Append items at beginning of dictionary
Given a dictionary, append another dictionary at beginning of it. Input : test_dict = {"Gfg" : 5, "is" : 3, "best" : 10}, updict = {"pre1" : 4} Output : {'pre1': 4, 'Gfg': 5, 'is': 3, 'best': 10} Explanation : New dictionary updated at front of dictionary. Input : test_dict = {"Gfg" : 5}, updict = {"pre1" : 4} Output : {'pre1': 4, 'Gfg': 5} Explana
3 min read
Python - Extract Dictionary Items with Summation Greater than K
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
5 min read
Python - Group Similar items to Dictionary Values List
Given a list of elements, perform grouping of similar elements, as different key-value lists in a dictionary. Input : test_list = [4, 6, 6, 4, 2, 2, 4, 8, 5, 8] Output : {4: [4, 4, 4], 6: [6, 6], 2: [2, 2], 8: [8, 8], 5: [5]} Explanation : Similar items grouped together on occurrences. Input : test_list = [7, 7, 7, 7] Output : {7 : [7, 7, 7, 7]} Ex
7 min read
Python - Get particular Nested level Items from Dictionary
Given a dictionary, extract items from a particular level. Examples: Input : {"Gfg" : { "n1": 3, "nd2": { "n2" : 6 }}, "is" : { "ne1": 5, "ndi2": { "ne2" : 8, "ne22" : 10 } }}, K = 2 Output : {'n2': 6, 'ne2': 8, 'ne22': 10} Explanation : 2nd nesting items are extracted. Input : {"Gfg" : { "n1": 3, "nd2": { "n2" : 6 }}, "is" : { "ne1": 5, "ndi2": {
4 min read
Python program to extract dictionary items for custom values
Given a dictionary, extract all the items that match given values in the list Example: Input : test_dict = {"Gfg" : 3, "is" : 5, "for" : 8, "Geeks" : 10, "Best" : 16 }, sub_list = [5, 4, 10, 20, 16, 8] Output : {'is': 5, 'Geeks': 10, 'Best': 16, "for" : 8} Explanation : All values matching list values extracted along with keys. Input : test_dict =
4 min read
Python program to multiply all the items in a dictionary
Python program to illustrate multiplying all the items in a dictionary could be done by creating a dictionary that will store all the key-value pairs, multiplying the value of all the keys, and storing it in a variable. Example: Input: dict = {'value1':5, 'value2':4, 'value3':3, 'value4':2, 'value5':1} Output: ans = 120 Input: dict = {'v1':10, 'v2'
2 min read
Python - Accessing Items in Lists Within Dictionary
Given a dictionary with values as a list, the task is to write a python program that can access list value items within this dictionary. Method 1: Manually accessing the items in the list This is a straightforward method, where the key from which the values have to be extracted is passed along with the index for a specific value. Syntax: dictionary
5 min read
Adding Items to a Dictionary in a Loop in Python
In Python, we can dynamically add items to a dictionary within a loop using the dictionary's key-value assignment. In this article, we will learn how to add Items to a Dictionary in a Loop using Python Programming. Below is an example to understand the problem statement. Example:Input: keys = ['Name', 'Website', 'Topic', 'Founded']values = ['Geeksf
3 min read
Practice Tags :
three90RightbarBannerImg