1

I have a dict of dict object. What is the best way to find keys associating with the min value of the object? For example:

myDict = {'a': {'n': 1, 'm' : 2, 'l' : 3}, 'b':{'m' = 2, 'l': 3, 'k':4}}
(firstKey, secondKey) = argmin(myDict)

The argmin should return 'a' and 'n' What I am doing now is:

minValue = 10
firstKey, secondKey = None, None
for k1 in myDict.keys():
    for k2 in myDict[k1].keys():
        if myDict[k1][k2] < minValue:
            minValue = myDict[k1][k2]
            firstKey, secondKey = k1, k2
vad
  • 344
  • 2
  • 12

2 Answers2

0

This works and leaves most work to python build ins:

def helper(k_d):
    key, d = k_d
    mi = min(d, key=d.get)
    v = d[mi]
    return ((key, mi), v)

d = {'a': {'n': 1, 'm': 2, 'l': 3}, 'b': {'m': 2, 'l': 3, 'k': 4}}
min_dict = dict(map(helper, d.items()))
result = min(min_dict, key=min_dict.get)

This is build around this answer. Helper will take a tuple of key and dict, find the key (mi) of the passed dict with the minimal value and return it along with the value (v) and the first-level key (key).

Robsdedude
  • 1,292
  • 16
  • 25
0

This will work for both keys

my_dict = {'a': {'n': 1, 'm' : 2, 'l' : 3}, 'b':{'m': 2, 'l': 3, 'k':4}}

smallest = {i: min(my_dict[i].values()) for i in my_dict}
for k, v in my_dict.items():
    print(k, *[i for i in v if v[i] == smallest[k]])

# a n
# b m
vash_the_stampede
  • 4,590
  • 1
  • 8
  • 20