Python:通过元组键返回字典的最大值
我有一个字典,内容如下:
counts = {('test1', 'alpha'): 2,
('test2', 'beta'): 1,
('test1', 'delta'): 1,
('test2', 'gamma'): 2}
我该如何返回每个元组中值最大的那个'alpha/beta/gamma/delta'呢?
也就是说:
test1, alpha, 2 #因为test1的'alpha'值最高
test2, gamma, 2 #因为test2的'gamma'值最高
这样做可以吗?
maxDict={}
for (eachtest,pattern), counter in counts.items():
maxDict[eachtest,pattern] = max(maxDict.get(eachtest,0),counter)
谢谢。
2 个回答
2
首先,把你的字典转换成一个可以把测试名称映射到包含 (数量, 模式)
元组的列表中:
counts2 = collections.defaultdict(list)
for (test, pattern), c in counts.iteritems():
counts2[test] += (c, pattern)
现在你可以很简单地找到最大值了:
for test, patterns in counts2.iteritems():
print test, max(patterns)
1
你说得差不多对。你只需要用测试名称来索引字典,同时把模式名称和它的值都记下来,作为字典的值。我觉得这里用max
有点过于复杂了。其实用更简单的代码也能实现,而且更容易理解:
maxDict = {}
for (eachtest, pattern), counter in counts.iteritems():
_, prev_max = maxDict.get(eachtest, ('', 0))
if counter > prev_max:
maxDict[eachtest] = (pattern, counter)
print maxDict
# prints: {'test1': ('alpha', 2), 'test2': ('gamma', 2)}