Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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) 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading