Home > Blockchain >  How to Find Max Value in a Dictionary of Dictionaries and Turn it Into a Tuple?
How to Find Max Value in a Dictionary of Dictionaries and Turn it Into a Tuple?

Time:01-30

I have a function nestedmax that has the following...

Parameters: A dictionary of dictionaries, and a string indicating the subfield we care about.
Returns: A tuple (x, y) where x = primary key, and y = max value in the subfield.

Sample input: {"1/3" : {"X" : 9}, "1/4" : {"X" : 12}}, "X"
Desired output: ("1/4", 12)

Sample input: {"1/1" : {"opponent": "BU", "X" : 4}, "1/2" : {"opponent": "HC", "X" : 3}}, "X"
Desired output: ("1/1", 4)

I currently have...

def nestedmax(input_dict, subfield):

  my_dict = input_dict.copy()
  for d in my_dict.values():
      for field in list(d.keys()):
          if field not in subfield:
              d.pop(field)
  return(my_dict)

But can't seem to turn my output into a tuple like the desired output. Please help.

CodePudding user response:

I rewrote it for you. This will work

def nextedmax(input_dict, subfield):
    ini, s = 0, {}
    for k,v in my_dict.items():
        x_i = v[subfield]
        if x_i > ini:
            ini = x_i
            s = (k, ini)
    return (s) 

CodePudding user response:

Get the max item from dict, create the disired tuple

def nestedmax(input_dict, subfield):
  max_item = max(input_dict.items(), key=lambda x: x[1][subfield])
  return (max_item[0], max_item[1][subfield])

nestedmax({"1/1" : {"opponent": "BU", "X" : 4},  "1/2" : {"opponent": "HC", "X" : 3}}, "X") # ('1/1', 4)
nestedmax({"1/3" : {"X" : 9}, "1/4" : {"X" : 12}}, "X") #('1/4', 12)

CodePudding user response:

Store all the matching values and get the max value as a tuple

from operator import itemgetter

def nestedmax(input_dict, subfield):
    values = []
    for outer_k, outer_v in input_dict.items():
        for inner_k, inner_v in outer_v.items():
            if inner_k == subfield:
                values.append((outer_k, inner_v))
    return max(values, key=itemgetter(1))

CodePudding user response:

One way is to make generator of desired tuples from source and find maximum based on target value:

def nestedmax(source, target):
    stream = ((k, v[target]) for k, v in source.items())
    return max(stream, key=lambda x: x[1])
  •  Tags:  
  • Related