Basically i have a dictionary with 6 values and i want to get the two smallest values out to eliminate them. How can i get the two smallest values from the dictionary.
I have already tried using: min(eleminate.items(), key=lambda x: x[1]) but this only works once for me. The second value does not come.
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!")
My code prints out the same value twice. For example:
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!
There are a few ways to do this.
I would use sorted
:
from operator import itemgetter
print(sorted(data.items(), key=itemgetter(1))[:2])
Output:
[('Couple1', 3), ('Couple2', 6)]
To get the dictionary without those two items:
dict(sorted(data.items(), key=itemgetter(1))[2:]))
Output:
{'Couple3': 9, 'Couple4': 12, 'Couple5': 15, 'Couple6': 18}
Start by sorting your dictionary by value using sorted
on values
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)]
Then delete the first two elements in the sorted list
for key, value in sorted_eleminate[0:2]:
del eleminate[key]
print(eleminate)
#{'Couple3': 9, 'Couple4': 12, 'Couple5': 15, 'Couple6': 18}
Or just get the dictionary without the first two elements
print(dict(sorted_eleminate[2:]))
#{'Couple3': 9, 'Couple4': 12, 'Couple5': 15, 'Couple6': 18}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.