Tuesday, November 19, 2024
Google search engine
HomeLanguagesPython Program to get value of a dictionary given by index of...

Python Program to get value of a dictionary given by index of maximum value of given key

Given a dictionary with value as a list, the task is to write a Python program that can find the maximum of any one key and output a similar index column of other key’s values.

Approach :

  • Get the maximum of the given key.
  • Get the index of the maximum element found.
  • Check if the index of max is present in the search key, if not, return Result not Possible.
  • Get the element on the search key ( opt_key), which is at the index found in Step 2.

Input : test_dict = {“gfg” : [4, 1, 6], “is” : [1, 4, 8], “best” : [9, 10, 1]}, max_search = “best”, opt_key = “gfg”
Output : 1
Explanation : 10 is maximum element in best key, which corresponds to 1st index. In gfg, 1st index is 1, hence 1.

Input : test_dict = {“gfg” : [4, 10, 6], “is” : [1, 4, 8], “best” : [9, 10, 1]}, max_search = “best”, opt_key = “gfg”
Output : 10
Explanation : 10 is maximum element in best key, which corresponds to 1st index. In gfg, 1st index is 10, hence 10.

Method 1 : Using index(), max() and lambda

In this, we find the maximum of max search key using max() and get its index using index(), and then get the value of index in output key. 

Example:

Python3




# initializing dictionary
test_dict = {"gfg": [4], "is": [1, 4, 8], "best": [9, 10]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing max_search key
max_search = "best"
 
# initializing output key
opt_key = "gfg"
 
# handling case in which maximum index is not
# present in output key
if len(test_dict[opt_key]) <= test_dict[max_search].index(
  max(test_dict[max_search])):
    res = "Result not possible"
 
# using max() to get of search key
else:
    res = max(test_dict[opt_key], key=lambda sub: test_dict[max_search]
              [test_dict[opt_key].index(sub)])
 
# printing result
print("The required output : " + str(res))


Output

The original dictionary is : {'gfg': [4], 'is': [1, 4, 8], 'best': [9, 10]}
The required output : Result not possible

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

Method 2 : Using zip() and max()

In this, the lists of both the search and output keys are combined using zip(), post that a maximum of one list is found and the corresponding index of output key is returned. 

Example:

Python3




# initializing dictionary
test_dict = {"gfg": [4, 1, 6], "is": [1, 4, 8], "best": [9, 10, 1]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing max_search key
max_search = "best"
 
# initializing output key
opt_key = "gfg"
 
# handling case in which maximum index is not present
# in output key
if len(test_dict[opt_key]) <= test_dict[max_search].index(
  max(test_dict[max_search])):
    res = "Result not possible"
 
# using max() to get of search key
# zip() used for combining lists
else:
    res = max(zip(test_dict[opt_key], test_dict[max_search]),
              key=lambda sub: sub[1])[0]
 
# printing result
print("The required output : " + str(res))


Output

The original dictionary is : {'gfg': [4, 1, 6], 'is': [1, 4, 8], 'best': [9, 10, 1]}
The required output : 1

Time complexity: O(n), where n is the length of the largest list in the dictionary. 
Auxiliary space: O(1).

Method 3: Using simple for loop + max()

Checks if the maximum value in the max_search key is present in the output key, and if not, returns “Result not possible”. If the maximum value is present, it uses a lambda function and max() to get the maximum value in the output key that satisfies two conditions: it is present in the max_search key, and its count in the max_search key is equal to the count of the maximum value in the max_search key.

Python3




# initializing dictionary
test_dict = {"gfg": [4], "is": [1, 4, 8], "best": [9, 10]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing max_search key
max_search = "best"
 
# initializing output key
opt_key = "gfg"
 
# handling case in which maximum index is not
# present in output key
if len(test_dict[opt_key]) <= test_dict[max_search].index(
  max(test_dict[max_search])):
    res = "Result not possible"
 
# using list comprehension and max() to get the
# maximum value in opt_key that satisfies the condition
else:
    res = max(test_dict[opt_key], key=lambda sub:
              (sub in test_dict[max_search],
              test_dict[max_search].count(max(test_dict[max_search]))
              == test_dict[max_search].count(sub)))
 
# printing result
print("The required output : " + str(res))


Output

The original dictionary is : {'gfg': [4], 'is': [1, 4, 8], 'best': [9, 10]}
The required output : Result not possible

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

Method 4: Using List Comprehension and Sorting

This approach involves using list comprehension to create a new list of tuples with the keys and their corresponding values in descending order of their maximum value. Then, we can iterate through this list to find the first key that satisfies the condition and return its maximum value.

Python3




# initializing dictionary
test_dict = {"gfg": [4], "is": [1, 4, 8], "best": [9, 10]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing max_search key
max_search = "best"
 
# initializing output key
opt_key = "gfg"
 
# handling case in which maximum index is not
# present in output key
if len(test_dict[opt_key]) <= test_dict[max_search].index(max(test_dict[max_search])):
    res = "Result not possible"
 
else:
    # create a list of tuples with keys and their corresponding values in descending order of their maximum value
    lst = [(key, max(val)) for key, val in test_dict.items()]
    lst.sort(key=lambda x: x[1], reverse=True)
 
    # iterate through the list to find the first key that satisfies the condition and return its maximum value
    for key, val in lst:
        if key != opt_key and max_search in test_dict[key]:
            res = val
            break
 
# printing result
print("The required output : " + str(res))


Output

The original dictionary is : {'gfg': [4], 'is': [1, 4, 8], 'best': [9, 10]}
The required output : Result not possible

Time complexity: O(n log n) due to sorting
Auxiliary space: O(n) for the list of tuples

Method 5: using the enumerate() function and a for loop. 

Here are the steps:

  1. Initialize max_search and opt_key as before.
  2. Initialize two variables max_val and max_index to store the maximum value and its index respectively. Set max_val to -1 initially.
  3. Loop through the values of opt_key using enumerate(). For each value, check if it is present in the max_search key of the dictionary using in.
  4. If it is, get its index in the max_search key using index() and store it in a variable curr_index.
  5. If curr_index is greater than max_index, update max_index and max_val to curr_index and the current value respectively.
  6. If no value in opt_key is present in max_search, set res to “Result not possible”.
  7. If a value in opt_key is present in max_search, set res to max_val.
  8. Print the result.

Python3




# initializing dictionary
test_dict = {"gfg": [4], "is": [1, 4, 8], "best": [9, 10]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing max_search key
max_search = "best"
 
# initializing output key
opt_key = "gfg"
 
# initializing result
res = None
 
# initializing max value and index
max_val = -1
max_index = -1
 
# loop through values of opt_key
for idx, val in enumerate(test_dict[opt_key]):
    if val in test_dict[max_search]:
        curr_index = test_dict[max_search].index(val)
        if curr_index > max_index:
            max_index = curr_index
            max_val = val
 
# set result
if max_val == -1:
    res = "Result not possible"
else:
    res = max_val
 
# printing result
print("The required output : " + str(res))


Output

The original dictionary is : {'gfg': [4], 'is': [1, 4, 8], 'best': [9, 10]}
The required output : Result not possible

Time complexity: O(n), where n is the number of values in opt_key.
Auxiliary space: O(1), since we are using only a few variables to store the maximum value and its index.

Method 6: Using itertools.chain() and max()

  • Import the itertools module.
  • Use the chain() function from itertools to combine all the values in the dictionary into a single list.
  • Use the max() function to find the maximum value in the list.
  • Iterate through the dictionary and find the key that contains the maximum value.
    • Check if the key contains the max_search value.
    • If the key contains the max_search value, return the maximum value.
    • If the key does not contain the max_search value, continue iterating through the dictionary until a key that contains the max_search value is found.
    • If no key is found that contains the max_search value, return “Result not possible”.

Python3




# importing itertools module
import itertools
 
# initializing dictionary
test_dict = {"gfg": [4], "is": [1, 4, 8], "best": [9, 10]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing max_search key
max_search = "best"
 
# initializing output key
opt_key = "gfg"
 
# using chain() function to combine all values in the dictionary into a single list
combined_list = list(itertools.chain(*test_dict.values()))
 
# finding the maximum value in the list
max_val = max(combined_list)
 
# initializing result
res = "Result not possible"
 
# iterating through the dictionary to find the key that contains the maximum value
for key, val in test_dict.items():
    if max_val in val:
        # if the key contains the max_search value, return the maximum value
        if key != opt_key and max_search in val:
            res = max_val
            break
        # if the key does not contain the max_search value, continue iterating through the dictionary
        elif key != opt_key and max_search not in val:
            continue
 
# printing result
print("The required output : " + str(res))


Output

The original dictionary is : {'gfg': [4], 'is': [1, 4, 8], 'best': [9, 10]}
The required output : Result not possible

Time complexity: O(n), where n is the number of elements in the dictionary.
Auxiliary space: O(n), where n is the number of elements in the dictionary, to store the combined list of values from the 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