如何通过(唯一键和最大值)从字典中提取所有值?
示例:
{('117', 14): 10, ('113', 11): 5, ('117', 16): 3, ('113', 5): 1}
输出将是:
{('117', 14): 10, ('113', 11): 5}
答案 0 :(得分:2)
您可以使用itertools.groupby
:
import itertools
d = {('117', 14): 10, ('113', 11): 5, ('117', 16): 3, ('113', 5): 1}
new_d = [list(b) for _, b in itertools.groupby(sorted(d.items(), key=lambda x:x[0][0]), key=lambda x:x[0][0])]
final_result = dict(max(i, key=lambda x:x[-1]) for i in new_d)
输出:
{('113', 11): 5, ('117', 14): 10}