0

I am trying to sort a dictionary into an order with negative numbers. This seems like an easy task but for some reason I can't get it. I've seen a few similar solutions but they're either not exactly what I'm looking for or I can't get them to work for me. I know it is something to do with the key but I don't know what. I would preferably want the final output to be a list if possible.

number1 = 1
number2 = -5
number3 = -2
number4 = 3

my_dict = {"a" : number1,
           "b" : number2,
           "c" : number3,
           "d" : number4
           }

sorted_dict = sorted(my_dict, key= ???)

I would want something like:

#output
['b', 'c', 'a', 'd']
#so -5 -2 1 3
Chopperdom
  • 13
  • 1

2 Answers2

2

You want to sort on the values not the keys. Use:

sorted_dict = sorted(my_dict, key= my_dict.get)
print(sorted_dict)

to give:

['b', 'c', 'a', 'd']
user19077881
  • 3,643
  • 2
  • 3
  • 14
0

Something like this ought to do it

sorted(my_dict.keys(), key=lambda x: my_dict[x])

The key argument in sorted needs to be a function that accepts each element of the first positional argument. It sorts the first argument based on the output of that function.