2

For example, if the given dictionary is as following:

dic = {('K1', 'S1'): 4.999997655759467, 
       ('k1', 'K2'): 6.1999036349232375, 
       ('K1', 'K4'): 7.999999999999876, 
       ('K2', 'K1'): 6.199940422452897, 
       ('K2', 'K3'): 7.999999999999876, 
       ('K2', 'K5'): 6.199962763954776, 
       ('K3', 'K2'): 6.199997321675397, 
       ('K3', 'K6'): 7.999998023783301, 
       ('K3', 'S2'): 9.999999999999911, 
       ('K4', 'S1'): 9.999999999999911, 
       ('K4', 'K1'): 6.199999975663285, 
       ('K4', 'K5'): 6.19999999303405, 
       ('K5', 'K2'): 6.199989058277423, 
       ('K5', 'K4'): 7.999999999999876, 
       ('K5', 'K6'): 7.999950953156936, 
       ('K6', 'S2'): 9.999999999999911, 
       ('K6', 'K3'): 7.999641214892367, 
       ('K6', 'K5'): 6.19980050493078}

And the required output is as follows:

{('K1', 'K4'): 7.999999999999876,
 ('K2', 'K3'): 7.999999999999876,
 ('K3', 'S2'): 9.999999999999911,
 ('K4', 'S1'): 9.999999999999911,
 ('K5', 'K4'): 7.999999999999876,
 ('K6', 'S2'): 9.999999999999911}

I implemented the following function, but unfortunately it can only get the value and it doesn't get the corresponding key.

def getMaxForX(number):
    return max([v for k, v in dic.items() if k[0] == number])

I don't fully understand the concept of max key and values for a dictionary?

Please suggest how I can fix this.

ekhumoro
  • 115,249
  • 20
  • 229
  • 336
Leekhamxay
  • 23
  • 3

2 Answers2

0

I guess you are only appending value (v) not key (k). So update your logic of return to

return max([k, v for k, v in Q_values.items() if k[0] == number])
Yash Khatri
  • 27
  • 1
  • 2
  • This gives an error as well as with the this: return max([[k, v] for k, v in dic.items() if k[0] == number]) it shows ValueError: max() arg is an empty sequence – Leekhamxay Nov 12 '19 at 13:37
0

So you want to group by the first element of the key (K1, K2, K3, ...), and then find the maximum of each group based on the value:

>>> from itertools import groupby
>>> sortkey = lambda i: i[0][0].lower()
>>> groups = groupby(sorted(dic.items(), key=sortkey), key=sortkey)
>>> result = dict(max(v, key=lambda i: i[1]) for k, v in groups)
>>> result
{('K1', 'K4'): 7.999999999999876, ('K2', 'K3'): 7.999999999999876, ('K3', 'S2'): 9.999999999999911, ('K4', 'S1'): 9.999999999999911, ('K5', 'K4'): 7.999999999999876, ('K6', 'S2'): 9.999999999999911}

NB: I used a sortkey when grouping because one of the keys in your example has a different case. If that was just a typo, you can omit it.

ekhumoro
  • 115,249
  • 20
  • 229
  • 336