Search code examples
pythondictionaryminimum

Retrieve keys corresponding to minimum value in nested dict of dicts


This answer explains how to get the key corresponding to a minium value in a dictionary.

How would you extend this to get the keys of the minimum value in a dict of dicts?

For example, say we have a dictionary of dictionaries:

d = {
     3: {5: 0.6, 37: 0.98, 70: 0.36},
     5: {5: 2.67, 37: 0.01, 70: 0.55},
     7: {5: 0.2, 37: 0.3, 70: 1.2}
    }

How can I obtain the keys (5,37) of the outer and inner dictionaries respectively corresponding to the minimum value of 0.01? Is there a pythonic way to do this?


Solution

  • One way is to restructure your dictionary and use a list comprehension to retrieve the keys with minimum value:

    d = {
         3: {5: 0.6, 37: 0.98, 70: 0.36},
         5: {5: 2.67, 37: 0.01, 70: 0.55},
         7: {5: 0.2, 37: 0.3, 70: 1.2}
        }
    
    res_dict = {}
    
    for k, v in d.items():
        for k2, v2 in v.items():
            res_dict[(k, k2)] = v2
    
    minval = min(res_dict.values())
    res = [k for k, v in res_dict.items() if v == minval]
    
    print(res)
    # [(5, 37)]