Monday, November 18, 2024
Google search engine
HomeLanguagesPython program to get maximum of each key Dictionary List

Python program to get maximum of each key Dictionary List

Given a list of dictionaries, write a Python program to get the maximum of each key.

Examples:

Input : test_list = [{“Gfg” : 8, “is” : 1, “Best” : 9}, {“Gfg” : 2, “is” : 9, “Best” : 1}, {“Gfg” : 5, “is” : 10, “Best” : 7}] 
Output : {‘Gfg’: 8, ‘is’: 10, ‘Best’: 9} 
Explanation : Maximum of Gfg key is 8 among possible 8, 2 and 5. 

Input : test_list = [{“Gfg” : 8, “is” : 1, “Best” : 9}, {“Gfg” : 5, “is” : 10, “Best” : 7}] 
Output : {‘Gfg’: 8, ‘is’: 10, ‘Best’: 9} 
Explanation : Maximum of Best key is 7 among possible 9, 7. 

Method #1 : Using items() + loop + max()

In this, we iterate for each dictionary and keys in them using loop and keep updating maximum values for each key using max().

Python3




# Python3 code to demonstrate working of
# All Keys Maximum in Dictionary List
# Using items() + loop + max()
 
# initializing Matrix
test_list = [{"Gfg": 8, "is": 1, "Best": 9},
             {"Gfg": 2, "is": 9, "Best": 1},
             {"Gfg": 5, "is": 10, "Best": 7}]
 
# printing original list
print("The original list is : " + str(test_list))
 
 
res = {}
for dic in test_list:
    for key, val in dic.items():
 
        # checking for key presence and updating max
        if key in res:
            res[key] = max(res[key], val)
        else:
            res[key] = val
 
# printing result
print("All keys maximum : " + str(res))


Output:

The original list is : [{‘Gfg’: 8, ‘is’: 1, ‘Best’: 9}, {‘Gfg’: 2, ‘is’: 9, ‘Best’: 1}, {‘Gfg’: 5, ‘is’: 10, ‘Best’: 7}] All keys maximum : {‘Gfg’: 8, ‘is’: 10, ‘Best’: 9}The original list is : [{‘Gfg’: 8, ‘is’: 1, ‘Best’: 9}, {‘Gfg’: 2, ‘is’: 9, ‘Best’: 1}, {‘Gfg’: 5, ‘is’: 10, ‘Best’: 7}] All keys maximum : {‘Gfg’: 8, ‘is’: 10, ‘Best’: 9}

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

Method #2 : Using defaultdict()

In this, we omit step of conditional check for key existence by using defaultdict(). Rest all the functionalities are similar to above method.

Python3




# Python3 code to demonstrate working of
# All Keys Maximum in Dictionary List
# Using defaultdict()
from collections import defaultdict
 
# initializing Matrix
test_list = [{"Gfg": 8, "is": 1, "Best": 9},
             {"Gfg": 2, "is": 9, "Best": 1},
             {"Gfg": 5, "is": 10, "Best": 7}]
 
# printing original list
print("The original list is : " + str(test_list))
 
 
res = defaultdict(int)
for dic in test_list:
    for key, val in dic.items():
 
        # defaultdict helps to avoid conditional check here
        res[key] = max(res[key], val)
 
# printing result
print("All keys maximum : " + str(dict(res)))


Output:

The original list is : [{‘Gfg’: 8, ‘is’: 1, ‘Best’: 9}, {‘Gfg’: 2, ‘is’: 9, ‘Best’: 1}, {‘Gfg’: 5, ‘is’: 10, ‘Best’: 7}] All keys maximum : {‘Gfg’: 8, ‘is’: 10, ‘Best’: 9}

Time Complexity: O(n*n), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n), where n is the number of elements in the list “test_list”.

Method 3: using dictionary comprehension

Approach:

  1. Initialize the list of dictionaries.
  2. Use dictionary comprehension to create a new dictionary with the maximum value for each key.
  3. The key is obtained by iterating over the keys of the first dictionary in the list using the keys() method.
  4. The value is obtained by using the max() function to find the maximum value for that key in all the dictionaries in the list. This is done using a generator expression that iterates over the list of dictionaries and extracts the value for the current key from each dictionary.
  5. Print the resulting dictionary.

Python3




test_list = [{"Gfg": 8, "is": 1, "Best": 9},             {
    "Gfg": 2, "is": 9, "Best": 1},             {"Gfg": 5, "is": 10, "Best": 7}]
 
# Using dictionary comprehension
max_dict = {k: max(d[k] for d in test_list) for k in test_list[0].keys()}
 
print("All keys maximum: ", max_dict)


Output

All keys maximum:  {'Gfg': 8, 'is': 10, 'Best': 9}

Time complexity: O(NK), 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, to store the resulting dictionary.

Method #4: Using set() and max() with list comprehension

Step-by-step approach:

  • Convert the list of dictionaries into a set of all keys using set() function.
  • Loop through the set of keys and use list comprehension to get a list of values for each key from all dictionaries.
  • Use the max() function to find the maximum value from the list of values.
  • Create a dictionary using dictionary comprehension to store the maximum value for each key.
  • Print the final dictionary

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# All Keys Maximum in Dictionary List
# Using set() and max() with list comprehension
 
# initializing Matrix
test_list = [{"Gfg": 8, "is": 1, "Best": 9},
             {"Gfg": 2, "is": 9, "Best": 1},
             {"Gfg": 5, "is": 10, "Best": 7}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# create a set of all keys
all_keys = set().union(*test_list)
 
# create a dictionary to store the maximum value for each key
max_values = {key: max(dic.get(key, float('-inf')) for dic in test_list) for key in all_keys}
 
# printing result
print("All keys maximum : " + str(max_values))


Output

The original list is : [{'Gfg': 8, 'is': 1, 'Best': 9}, {'Gfg': 2, 'is': 9, 'Best': 1}, {'Gfg': 5, 'is': 10, 'Best': 7}]
All keys maximum : {'Gfg': 8, 'is': 10, 'Best': 9}

Time complexity: O(nklogk), where n is the number of dictionaries in the list and k is the maximum number of keys in a dictionary. 
Auxiliary space: O(k), where k is the maximum number of keys in a dictionary. We need to store the set of all keys and the dictionary to store the maximum value for each key.

Method #5: Using reduce() and lambda function from functools module

Steps:

  1. Import the “reduce” and “functools” modules.
  2. Initialize the “test_list” with dictionaries as elements.
  3. Print the original list using the print() function.
  4. Define a lambda function that takes two dictionaries and returns a new dictionary with the maximum value for each key.
  5. Use the “reduce” function to apply the lambda function to all dictionaries in the “test_list” and obtain a single dictionary with the maximum value for each key.
  6. Print the maximum values dictionary using the print() function.

Python3




# Python3 code to demonstrate working of
# All Keys Maximum in Dictionary List
# Using reduce() and lambda function
# from functools module
 
# import reduce and functools
from functools import reduce
 
# initializing Matrix
test_list = [{"Gfg": 8, "is": 1, "Best": 9},
             {"Gfg": 2, "is": 9, "Best": 1},
             {"Gfg": 5, "is": 10, "Best": 7}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# define lambda function to get maximum
# values for each key
def max_dict(dict1, dict2): return {key: max(dict1.get(key, float(
    '-inf')), dict2.get(key, float('-inf'))) for key in set(dict1.keys()) | set(dict2.keys())}
 
# use reduce function to get maximum values
# for all dictionaries in the list
max_values = reduce(max_dict, test_list)
 
# printing result
print("All keys maximum : " + str(max_values))


Output

The original list is : [{'Gfg': 8, 'is': 1, 'Best': 9}, {'Gfg': 2, 'is': 9, 'Best': 1}, {'Gfg': 5, 'is': 10, 'Best': 7}]
All keys maximum : {'Best': 9, 'Gfg': 8, 'is': 10}

Time Complexity: O(N*K*log(K)), where n is the length of the “test_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.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments