I have a list of names,x, and a list of scores,y, that correspond to the names.
x = {a,b,c,d,e,f,g,h,i,j,k}
y= {8,8,15,13,12,17,18,12,14,14}
So, a has score 8, b has scores 8, c has score 15, ..., k has score 14
I want to find the 5 smallest scores from the list,y, and get their name and have a print out similar to the following:
top5 lowest scores:
a : 8
b : 8
e : 12
h : 12
d : 13
Currently, I am creating a copy of the list and then using pop to keep reducing the list, but it is giving me incorrect names for the scores. However, when I create my list for the max5 values, everything comes out fine using the same method. I am unsure of a function that lets me do this in python. This is just a sample of my problem, my real problem involves store locations along with scores for those stores that I computed from a function, but I want to get the top 5 highest and 5 lowest scores. Does anyone have an efficient solution to this?
Python has a data structure called
Dictionary
that you can use to store key/value pairs . In Python , dictionary is defined as -Then you can iterate over the key value pairs in this dictionary to find the 5 smallest numbers.
You can convert the dict to a tuple and then sort the tuple based on the second item-
Instead of using a dict, you can also use a
list of tuples
, and use the last line in above code to sort it based on the second element of each tuple.The list of tuples would look like -