Home > Net >  Python: function to sort a dictionary by value and return only a key
Python: function to sort a dictionary by value and return only a key

Time:04-10

I need to write a function that takes a dictionary and returns the list of ONLY keys sorted descending by the value. So let's say I have: cars_1 = {"Opel": 1977, "Ford": 1965, "BWM": 1981, "Jaguar": 1971} and the result would be: [BMW, Opel, Jaguar, Ford] So the cars are sorted not by the name of the car but by the value.

And I don't want to import any built-in Python fuctions

So far I have this:

def cars_desc():
    cars_1 = {"Opel": 1977, "Ford": 1965, "BWM": 1981, "Jaguar": 1971}
    cars_2= sorted(cars_1.items(), key=lambda x: x[1], reverse=True)

for i in cars_2:
    print(i[0])

this returns good results but not list. Does anyone know how to return a list?

CodePudding user response:

You can use list comprehension instead

cars = [i[0] for i in cars_2]
print(cars)

CodePudding user response:

I think you can do this sorted(list(cars_1.items()), key=lambda x: x[1], reverse=True). The return value of .items() method is a view object so you need to convert it to list. Hope it helps.

  • Related