Open In App

Python – Value limits to keys in Dictionaries List

Given a Dictionaries list, write a Python program to assign limits to each key in dictionary list.( each having all keys ).

Examples:



Input : test_list = [{“gfg” : 4, “is” : 7, “best” : 10}, {“gfg” : 2, “is” : 5, “best” : 9}, {“gfg” : 1, “is” : 2, “best” : 6}] 
Output : {‘gfg’: [1, 4], ‘is’: [2, 7], ‘best’: [6, 10]} 
Explanation : gfg has min. value to be 1 and maximum to be 4.

Input : test_list = [{“gfg” : 4, “best” : 10}, {“gfg” : 2, “best” : 9}, {“gfg” : 1, “best” : 6}] 
Output : {‘gfg’: [1, 4], ‘best’: [6, 10]} 
Explanation : best has min. value to be 6 and maximum to be 10. 



Method #1 : Using max() + min() + loop + keys()

In this, we perform task of getting all keys using keys(), and min and max values for limits are computed using min() and max(). The iteration of all the dictionaries is carried out using loop.

Step-by-step approach

  1. Initialize a list of dictionaries called test_list which contains 3 dictionaries.
  2. Print the original list.
  3. Initialize an empty dictionary called res.
  4. Get all the keys from the first dictionary in test_list using the keys() method, and convert them into a list.
  5. Loop through each key in the keys list.
  6. For each key, use a list comprehension to extract the values of that key from all the dictionaries in test_list.
  7. Use the min() and max() functions to get the minimum and maximum values of that key, respectively.
  8. Assign a list of [min_value, max_value] to the res dictionary for that key.
  9. Print the final dictionary res which contains the ranges for each key.




# Python3 code to demonstrate working of
# Value limits to keys in Dictionaries List
# Using max() + min() + loop + keys()
 
# initializing Matrix
test_list = [{"gfg": 4, "is": 7, "best": 10},
             {"gfg": 2, "is": 5, "best": 9},
             {"gfg": 1, "is": 2, "best": 6}]
 
# printing original list
print("The original list is : " + str(test_list))
 
res = dict()
 
# extraction of all keys
keys = list(test_list[0].keys())
 
for key in keys:
 
    # assigning ranges to each key
    res[key] = [min(sub[key] for sub in test_list), max(sub[key]
                                                        for sub in test_list)]
 
# printing result
print("Keys Ranges : " + str(res))

Output
The original list is : [{'gfg': 4, 'is': 7, 'best': 10}, {'gfg': 2, 'is': 5, 'best': 9}, {'gfg': 1, 'is': 2, 'best': 6}]
Keys Ranges : {'gfg': [1, 4], 'is': [2, 7], 'best': [6, 10]}

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

Method #2 : Using dictionary comprehension + min() + max() + keys()

Step-by-step approach:

Below is the implementation of the above approach:




# Python3 code to demonstrate working of
# Value limits to keys in Dictionaries List
# Using list comprehension + min() + max() + keys()
 
# initializing Matrix
test_list = [{"gfg": 4, "is": 7, "best": 10},
             {"gfg": 2, "is": 5, "best": 9},
             {"gfg": 1, "is": 2, "best": 6}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# extraction of all keys
keys = list(test_list[0].keys())
 
# Dictionary comprehension used as one liner to perform task
res = {key: [min(sub[key] for sub in test_list), max(sub[key]
                                                     for sub in test_list)] for key in keys}
 
# printing result
print("Keys Ranges : " + str(res))

Output
The original list is : [{'gfg': 4, 'is': 7, 'best': 10}, {'gfg': 2, 'is': 5, 'best': 9}, {'gfg': 1, 'is': 2, 'best': 6}]
Keys Ranges : {'gfg': [1, 4], 'is': [2, 7], 'best': [6, 10]}

Time complexity: O(n*m), where n is the number of dictionaries in the list and m is the average number of keys in each dictionary.
Auxiliary space: O(m), where m is the number of keys in each dictionary.

Method 3: Using collections.defaultdict

This method uses the collections.defaultdict class to simplify the process of finding the minimum and maximum values for each key:

First create a defaultdict object that automatically initializes new keys with a pair of extreme values: positive infinity and negative infinity. Then, loop through each sub-dictionary in test_list and update the minimum and maximum values for each key in the corresponding dictionary in res. Finally, convert res to a regular dictionary before printing the result.

Step-by-step approach:

Below is the implementation of the above approach:




from collections import defaultdict
 
# initializing Matrix
test_list = [{"gfg": 4, "is": 7, "best": 10},
             {"gfg": 2, "is": 5, "best": 9},
             {"gfg": 1, "is": 2, "best": 6}]
 
# printing original list
print("The original list is : " + str(test_list))
 
res = defaultdict(lambda: [float('inf'), float('-inf')])
 
for sub_dict in test_list:
    for key, val in sub_dict.items():
        res[key][0] = min(res[key][0], val)
        res[key][1] = max(res[key][1], val)
 
# printing result
print("Keys Ranges : " + str(dict(res)))

Output
The original list is : [{'gfg': 4, 'is': 7, 'best': 10}, {'gfg': 2, 'is': 5, 'best': 9}, {'gfg': 1, 'is': 2, 'best': 6}]
Keys Ranges : {'gfg': [1, 4], 'is': [2, 7], 'best': [6, 10]}

Time complexity: O(n * k), where n is the number of dictionaries in the input list and k is the average number of keys in each dictionary.
Auxiliary space: O(k), where k is the number of keys in each dictionary, because we are storing a pair of extreme values for each key in the defaultdict.

Method #4: Using pandas DataFrame

This approach may be useful if you have more complex data to work with, as pandas provides a wide range of tools for data manipulation and analysis.




import pandas as pd
 
# initializing Matrix
test_list = [{"gfg": 4, "is": 7, "best": 10},
             {"gfg": 2, "is": 5, "best": 9},
             {"gfg": 1, "is": 2, "best": 6}]
 
# create a DataFrame from the list of dictionaries
df = pd.DataFrame(test_list)
 
# get the minimum and maximum value for each column
res = {col: [df[col].min(), df[col].max()] for col in df.columns}
 
# printing result
print("Keys Ranges : " + str(res))

OUTPUT:
Keys Ranges : {'gfg': [1, 4], 'is': [2, 7], 'best': [6, 10]}

Time complexity: O(nm), where n is the number of dictionaries in the list and m is the number of keys in each dictionary.
Auxiliary space: O(nm), as we create a DataFrame from the list of dictionaries.

Method #5: Using list comprehension and built-in functions min() and max()

This program calculates the minimum and maximum values for each key in a list of dictionaries and stores the result in a new dictionary. It then prints the dictionary containing the range of values for each key.




test_list = [{"gfg": 4, "is": 7, "best": 10},             {"gfg": 2, "is": 5, "best": 9},             {"gfg": 1, "is": 2, "best": 6}]
 
res = {}
 
for key in test_list[0].keys():
    values = [d[key] for d in test_list]
    res[key] = [min(values), max(values)]
 
print("Keys Ranges : " + str(res))

Output
Keys Ranges : {'gfg': [1, 4], 'is': [2, 7], 'best': [6, 10]}

Time complexity: O(n*m), where n is the number of keys in the first dictionary and m is the length of the test_list.
Auxiliary space: O(n), where n is the number of keys in the first dictionary. 

Method #6: Using nested loop

Step-by-step approach:

Below is the implementation of the above approach:




# Python3 code to demonstrate working of
# Value limits to keys in Dictionaries List
# Using nested loop
 
# initializing Matrix
test_list = [{"gfg": 4, "is": 7, "best": 10},
             {"gfg": 2, "is": 5, "best": 9},
             {"gfg": 1, "is": 2, "best": 6}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# extracting all keys
keys = list(test_list[0].keys())
 
# initializing result dictionary with empty lists
res = {key: [] for key in keys}
 
# iterating through each dictionary in the list
for sub in test_list:
    # iterating through each key in the dictionary
    for key in keys:
        # adding the value of the key to the list for that key in the result dictionary
        res[key].append(sub[key])
 
# computing the min and max for each key and storing the range in the result dictionary
for key in keys:
    res[key] = [min(res[key]), max(res[key])]
 
# printing result
print("Keys Ranges : " + str(res))

Output
The original list is : [{'gfg': 4, 'is': 7, 'best': 10}, {'gfg': 2, 'is': 5, 'best': 9}, {'gfg': 1, 'is': 2, 'best': 6}]
Keys Ranges : {'gfg': [1, 4], 'is': [2, 7], 'best': [6, 10]}

Time complexity: O(n * k), where n is the number of dictionaries in the list and k is the number of keys in each dictionary. 
Auxiliary space: O(k), where k is the number of keys in each dictionary.


Article Tags :