I'm pretty new to this - I'm working on a basic sales csv file to extract multiple values.. The csv contains a list of months and the number of sales for that month as well as other columns but these are the only two I'm working with below.
I was wondering how I might be able to return two corresponding fields?
Below is some working code where I am getting the highest sales figure for a month - I also want to return the month name itself next to the figure.. I've tried a few things but I haven't managed to get it to work.
Any help and advice would be appreciated!! :)
header = ["year", "month", "sales", "expenditure"]
def run():
data = read_data()
sales = []
for row in data:
min_sale = int(row["sales"])
sales.append(min_sale)
minny = min(sales)
print("Minimum sales is month: {}".format(minny))
run()
You can continue down the path of appending to a list then picking the smallest. Instead of appending to a list of only integers (sales numbers), you'll append a tuple of the sales number and the month:
When you call
min(sales), the selection function will first compare the sales integer for any pair of tuples. If there's a smaller int, that one "wins". If both ints are equal, the comparison will move on to compare the month strings:Here's a complete sample:
That prints:
The next step might be to just call
min()on data, and provide akey=param that tells min specifically what to consider for finding the minimum:That prints the same as above.
minpasses each element of data (a "dict" row) tosales_int, which returns the int-ified sales number, that number is then used in the comparison to find the minimum. You can try making another func, likeexpenditure_intwhich returns an int-ified expenditure.If you wanted to break a tie by month name, like above:
You can use the same concept of passing a key function when sorting a list, too:
data.sort(key=sale_int).