0

I am trying to sort by the second element in a two dimensional list, where all the elements are strings. It seems one of the problems with my current sorting method is that it cannot sort string elements. How would I go about changing it to integer? If possible, I would also like to have the first element correlated to the highest second element printed out. '2001' in this instance.

sqrm_price= [['1999', '7951'], ['2000', '8868'], ['2001', '12502']] 


def highPrice(sqrm_price):
    sort_price = sorted(sqrm_price, key = lambda x: x[1], reverse=True)
    print("The year " + sqrm_price[-1] + " has the highest price with " + sort_price[0] + "$")      
        
highPrice(sqrm_price) 

My preferred output would be " The year 2001 has the highest price with 12502$"

Any help would be greatly appreciated!

1
  • 1
    sorted(sqrm_price, key = lambda x: int(x[1]), reverse=True) Commented Oct 6, 2021 at 17:45

1 Answer 1

1

You can convert the string to an integer inside your lambda using int(). Also, why sort when you can max?

def highest_price(data):
    year, price = max(data, key=lambda item: int(item[1]))
    print(f"The year {year} has the highest price with ${price}")
# The year 2001 has the highest price with $12502
Sign up to request clarification or add additional context in comments.

1 Comment

I am new to pyhton and haven't heard about the 'max' method before, but it works very well. Thanks alot for your help!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.