我需要帮助从字典中获取最大值。我有一个{num:[state,value] ...字典,需要获取与最高值相关的所有内容。
#find max value in dictionary
td = {0: ['b',3], 1: ['b',6], 4: ['b',2], 3: ['b',5] }
#In this example td dict, I want to grab the key and state associated with the highest value, 6. I want to grab "1: ['b',6]"
print td
print td.keys()
print td.values()
maxval = max([v for k,[s,v] in td.iteritems()])
print maxval #correctly prints 6
答案 0 :(得分:5)
只需将max()
理解改为以第一个元素为值产生元组:
>>> max((v, k, s) for k, (s, v) in td.iteritems())
(6, 1, 'b')
所以你的代码看起来像这样:
maxval, maxnum, maxstate = max((v, k, s) for k, (s, v) in td.iteritems())
答案 1 :(得分:1)
>>> td = {0: ['b',3], 1: ['b',6], 4: ['b',2], 3: ['b',5] }
>>> max(td, key=lambda k:td[k][1])
1 ## This is the key with the maximum "value"
当然你也可以得到像这样的价值
>>> td[max(td, key=lambda k:td[k][1])]
['b', 6]
答案 2 :(得分:0)
print max(td.items(), key = lambda item: item[1][1])
key参数接受一个函数,如果使用它将产生最大化该函数的值。