# 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

 `# 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:

• Define a list of dictionaries named test_list with 3 dictionaries, each containing 3 key-value pairs.
• Print the original list using the print() function and the str() function to convert the list to a string.
• Extract all keys from the first dictionary in test_list using the keys() method and the list() function to convert the keys to a list. Store the result in a variable named keys.
• Use dictionary comprehension to create a new dictionary res that maps each key to a list containing the minimum and maximum values of that key in all dictionaries in test_list.
• The outer loop iterates over each key in keys.
• The inner loop iterates over each dictionary in test_list.
• Use a list comprehension to extract the value of the current key from each dictionary in test_list.
• Use the min() function and max() function to find the minimum and maximum value of the current key, respectively.
• Create a list of the minimum and maximum values and map it to the current key in res.
• Print the result using the print() function and the str() function to convert the dictionary to a string.

Below is the implementation of the above approach:

## Python3

 `# 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:

• Import the defaultdict class from the collections module.
• Define a list called test_list containing three dictionaries with three keys and corresponding values.
• Print the original list using the print() function and passing the string representation of test_list.
• Create a defaultdict object called res with a lambda function as its default factory. The lambda function returns a list containing two elements: the first element is set to float(‘inf’) (infinity) and the second element is set to float(‘-inf’) (negative infinity).
• Iterate over each dictionary sub_dict in test_list using a for loop.
• For each sub_dict, iterate over its keys and values using the items() method and a nested for loop.
• For each key-value pair, update the corresponding key in the res dictionary such that the first element of the list is the minimum value seen so far for that key, and the second element is the maximum value seen so far for that key. This is done using the min() and max() functions.
• Print the result using the print() function and passing the string representation of the resulting dictionary, which is obtained by converting res to a regular dictionary using the dict() function.

Below is the implementation of the above approach:

## Python3

 `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.

• Imports the pandas library and assigns it the alias pd.
• Creates a pandas DataFrame named df from the list of dictionaries test_list.
• Creates a dictionary named res using a dictionary comprehension that iterates over the columns of the DataFrame df.
• For each column, the dictionary comprehension creates a key-value pair where the key is the column name and the value is a list containing the minimum and maximum value of that column.
• Prints the resulting dictionary res as a string with the message “Keys Ranges : ” concatenated at the beginning.

## Python3

 `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.

## Python3

 `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:

• Create a list of dictionaries containing key-value pairs, representing the original data to be processed. This list is assigned to the variable test_list.
• Print the original list using the print() function and the str() function to convert the list to a string.
• Extract all the keys from the first dictionary in the list test_list, using the keys() method. This returns a view object of all the keys in the dictionary.
• Convert the view object to a list using the list() constructor. This gives us a list of all the keys in the dictionary.
• Initialize an empty dictionary res that will store the result of the program. The keys of the dictionary are initialized to be the same as the keys in the first dictionary in the test_list, and the values are initialized as empty lists.
• Iterate through each dictionary in test_list using a for loop. This creates a new variable sub that represents each dictionary in the list.
• Iterate through each key in the dictionary using another for loop. This creates a new variable key that represents each key in the dictionary.
• Add the value of the key to the list for that key in the result dictionary. This is done by appending the value of sub[key] to the list in the res dictionary at the index key.
• Compute the minimum and maximum values for each key in the res dictionary. This is done using another for loop that iterates through each key in the dictionary. The min() and max() functions are used to compute the minimum and maximum values for the list at that key in the res dictionary.
• Store the range (i.e., minimum and maximum values) for each key in the res dictionary. This is done by setting the value of the key in the res dictionary to a list containing the minimum and maximum values.
• Print the result using the print() function and the str() function to convert the dictionary to a string.

Below is the implementation of the above approach:

## Python3

 `# 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.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Previous
Next