[英]Python dict sorting based on two values in dict
I have a dictionairy that is build as 我有一个字典
>> dict = {'foo':[20,15],'bar':[10,5],'is':[35,3],'a':[20,10],'word':[50,1]}
I want to find the key that has the highest of list value [0] and the lowest of value [1] .. (or an approximation of it) but its giving me a total brainfreeze 我想找到具有最高列表值[0]和最低列表值[1] ..(或近似值)的键,但是它给了我很大的脑力
So for this example the desired result would be 因此,对于此示例,预期结果将是
>> 'word':[50,1]
It has been suggested I should more clearly define my paramaters: right now I'm looking to print the top 10 highest results from the [0] value as long as the second value remains below 5 建议我应该更清楚地定义我的参数:现在,我希望从[0]值中打印出前10个最高结果,只要第二个值保持在5以下
Thank you for taking the time to read the question 感谢您抽出宝贵时间阅读问题
You can use max
function with a proper key function : 您可以将max
函数与适当的key函数配合使用:
>>> max(dict.items(),key=lambda x: (x[1][0],-x[1][1]))
('word', [50, 1])
Note that in this case the priority of x[1][0]
(max value) is more than second one,So for some dictionaries like following : 请注意,在这种情况下, x[1][0]
(最大值)的优先级大于第二个优先级,因此对于某些字典,如下所示:
>>> dict = { 'foo': [35,5], 'word': [60, 25]}
It will returns : 它将返回:
('word', [60, 25])
You can also get items based on the difference of the values (which seems more close to what you want): 您还可以根据值的差异(看起来更接近您想要的)获得项目:
>>> dict = { 'foo': [70,5], 'word': [68,1]}
>>> max(dict.items(),key=lambda x: (x[1][0]-x[1][1]))
('word', [68, 1])
Try with below code. 尝试下面的代码。 I am not sure whether it satisfies all your scenarios 我不确定它是否满足您的所有情况
dict = {'a': [20, 10], 'word': [50, 1], 'is': [35, 3], 'foo': [20, 15], 'bar': [10, 5]}
value = max(dict.values())
b = value[1]
for each in dict.values():
if value[0] == each[0] and each[1] < b:
value = each
print (dict.keys()[dict.values().index(value)],value)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.