sorting - How to sort and subset a python dictionary with compound key? -
i got python dictionary compound key (pri_key, sec_key) , value:
(123, 456): 45 (123, 457): 90 (124, 234): 70 (125, 87): 3 (125, 103): 56 (125, 897): 34
how sort value in descending order on each "pri_key", , list corresponding "sec_key" accordingly? expected result:
123: 457 456 124: 234 125: 103 897 83
the key here original sort. after that, can groupby
on primary key. construct sort, can key off tuple of (<primary-key>, -<value>)
(the negative sort values have same primary key in descending order):
from itertools import groupby operator import itemgetter sorted_keys = sorted(original_dict, key=lambda key: (key[0], -original_dict[key])) primary_key, key_group in groupby(sorted_keys, key=itemgetter(0)): print(primary_key, [key[1] key in key_group])
and, of course, if can print keys, can use construct dictionary (or other datastructure) using results :-).
here's demo terminal:
>>> original_dict = { ... (123, 456): 45, ... (123, 457): 90, ... (124, 234): 70, ... (125, 87): 3, ... (125, 103): 56, ... (125, 897): 34 ... } >>> >>> itertools import groupby >>> operator import itemgetter >>> sorted_keys = sorted(original_dict, key=lambda key: (key[0], -original_dict[key])) >>> primary_key, key_group in groupby(sorted_keys, key=itemgetter(0)): ... print(primary_key, [key[1] key in key_group]) ... (123, [457, 456]) (124, [234]) (125, [103, 897, 87])
Comments
Post a Comment