Kristof Pal
Kristof Pal

Reputation: 1026

Get the max value for given keys in a dictionary?

I have the following list:

information = [[U1, b1, 12], [U1, b2, 15], [U1, b3, 1], [U2, b1, 6], [U2, b2, 7], [U2, b3, 43]]

I want to return a dictionary from this which will give me the highest values for a pair of U and b, in the case of the given list it would be:

bestvalues = {(U1, b2): 15, (U2, b3): 43}

how do I achieve this with simple python code, can not import extra modules.

Upvotes: 0

Views: 565

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121924

You'd need to sort (using sorted(), then group (using itertools.groupby(), then use max() on each group.

from operator import itemgetter
from itertools import groupby

key = itemgetter(0)
bestvalues = {tuple(best[:2]): best[2] 
              for key, group in groupby(sorted(information, key=key), key=key)
              for best in (max(group, key=itemgetter(2)),)}

These are all standard-library modules.

Without any imports, you'd have to loop twice; first to group everything, then to find the maximum value for each group:

grouped = {}
for tup in information:
    grouped.setdefault(tup[0], []).append(tup)

bestvalues = {}
for group in grouped.itervalues():
    best = max(group, key=lambda g: g[2])
    bestvalues[tuple(best[:2])] = best[2]

Demo:

>>> information = [['U1', 'b1', 12], ['U1', 'b2', 15], ['U1', 'b3', 1], ['U2', 'b1', 6], ['U2', 'b2', 7], ['U2', 'b3', 43]]
>>> key = itemgetter(0)
>>> {tuple(best[:2]): best[2] 
...               for key, group in groupby(sorted(information, key=key), key=key)
...               for best in (max(group, key=itemgetter(2)),)}
{('U1', 'b2'): 15, ('U2', 'b3'): 43}

or without imports:

>>> grouped = {}
>>> for tup in information:
...     grouped.setdefault(tup[0], []).append(tup)
... 
>>> bestvalues = {}
>>> for group in grouped.itervalues():
...     best = max(group, key=lambda g: g[2])
...     bestvalues[tuple(best[:2])] = best[2]
... 
>>> bestvalues
{('U1', 'b2'): 15, ('U2', 'b3'): 43}

Upvotes: 3

Related Questions