基本上,我有一个包含6个值的字典,我想获取两个最小值以消除它们。我如何从字典中获取两个最小值。
我已经尝试使用:min(eleminate.items(),key = lambda x:x [1]),但这对我来说只适用一次。第二个值不出现。
eleminate = {"Couple1":Couple1,"Couple2":Couple2,"Couple3":Couple3,"Couple4":Couple4,"Couple5":Couple5,"Couple6":Couple6}
eleminate.items()
FSmallest = min(eleminate.items(), key=lambda x: x[1])
SSmallest = min(eleminate.items(), key=lambda y: y[0])
print(eleminate)
gone = print(FSmallest," and ",SSmallest," have been eleminated!")
我的代码两次打印出相同的值。例如:
That was the end of Round one!
{'Couple1': 3, 'Couple2': 6, 'Couple3': 9, 'Couple4': 12, 'Couple5': 15, 'Couple6': 18}
('Couple1', 3) and ('Couple1', 3) have been eleminated!
答案 0 :(得分:2)
有几种方法可以做到这一点。
我会使用sorted
:
from operator import itemgetter
print(sorted(data.items(), key=itemgetter(1))[:2])
输出:
[('Couple1', 3), ('Couple2', 6)]
要获取字典而没有这两个项目:
dict(sorted(data.items(), key=itemgetter(1))[2:]))
输出:
{'Couple3': 9, 'Couple4': 12, 'Couple5': 15, 'Couple6': 18}
答案 1 :(得分:1)
首先对值使用sorted
对字典进行排序
import operator
eleminate = {'Couple1': 3, 'Couple2': 6, 'Couple3': 9, 'Couple4': 12, 'Couple5': 15, 'Couple6': 18}
sorted_eleminate = sorted(eleminate.items(), key=operator.itemgetter(1))
#[('Couple1', 3), ('Couple2', 6), ('Couple3', 9), ('Couple4', 12), ('Couple5', 15), ('Couple6', 18)]
然后删除排序列表中的前两个元素
for key, value in sorted_eleminate[0:2]:
del eleminate[key]
print(eleminate)
#{'Couple3': 9, 'Couple4': 12, 'Couple5': 15, 'Couple6': 18}
或者只获取没有前两个元素的字典
print(dict(sorted_eleminate[2:]))
#{'Couple3': 9, 'Couple4': 12, 'Couple5': 15, 'Couple6': 18}