1

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?

jpp
  • 159,742
  • 34
  • 281
  • 339
PyRsquared
  • 6,970
  • 11
  • 50
  • 86

1 Answers1

2

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)]
jpp
  • 159,742
  • 34
  • 281
  • 339
  • You never use your `v` variable. You can use `v` instead of `d[k]`. But more importantly, why not invert the dict and swap keys with values? You'd change `res_dict[(k, k2)] = v2` to `res_dict[v2] = (k, k2)` and then `minval = min(res_dict)` and `res = res_dict[minval]`. – Aran-Fey Apr 17 '18 at 17:53
  • 1
    @Aran-Fey, First point noted - thank you. Second point, what if there are multiple key combinations with the same value? Then you need to build a `defaultdict` of lists. Entirely possible, but may be overkill. – jpp Apr 17 '18 at 17:55
  • 1
    Ah, I see, your code lists all keys with the minimum value. I assumed it'd be enough to return just one of the keys with the minum value, if there are multiple. – Aran-Fey Apr 17 '18 at 17:58