python - Get the max value for given keys in a dictionary? -


i have following list:

information = [[u1, b1, 12], [u1, b2, 15], [u1, b3, 1], [u2, b1, 6], [u2, b2, 7], [u2, b3, 43]] 

i want return dictionary give me highest values pair of u , b, in case of given list be:

bestvalues = {(u1, b2): 15, (u2, b3): 43} 

how achieve simple python code, can not import modules.

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

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

these standard-library modules.

without imports, you'd have loop twice; first group everything, find maximum value each group:

grouped = {} tup in information:     grouped.setdefault(tup[0], []).append(tup)  bestvalues = {} 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]  ...               key, group in groupby(sorted(information, key=key), key=key) ...               best in (max(group, key=itemgetter(2)),)} {('u1', 'b2'): 15, ('u2', 'b3'): 43} 

or without imports:

>>> grouped = {} >>> tup in information: ...     grouped.setdefault(tup[0], []).append(tup) ...  >>> bestvalues = {} >>> 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} 

Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

css - Firefox for ubuntu renders wrong colors -