Home > front end >  Sorting dict - different result using dict.keys() instead of dict.items()
Sorting dict - different result using dict.keys() instead of dict.items()

Time:02-25

I am trying to sort a dictionary in python using sorted function, but my_dict.items() give me correct result and my_dict.keys() gives me incorrect

my_dict={"one":1, "two":2,"three":3, "four":4,"five":5}

sorted(my_dict.items(), key=lambda x:x[1], reverse=True)

Output:

[('five', 5), ('four', 4), ('three', 3), ('two', 2), ('one', 1)]

Above is correct, but I need only keys not the corresponding values, so I wrote:

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

Output:

['two', 'four', 'one', 'five', 'three']

Above is incorrect result, what I am doing wrong? Please help me with the right solution.

CodePudding user response:

You are throwing away the values too early - you need them for the sort. You can use your first solution and then select the first element in each tuple after sorting:

[key for key, value in sorted(my_dict.items(), key=lambda x:x[1], reverse=True)]

CodePudding user response:

In the first sort, you apply the function lambda x: x[1] to each element in my_dict.items(). my_dict.items() gives you (key, value) tuples, so you are sorting by value (integers in your case).

In the second sort, you are applying the function lambda x: x[1] to each element in my_dict.keys(). my_dict.keys() gives you strings, so you are sorting by the second character in each string.

Demo:

>>> my_dict = {"one":1, "two":2,"three":3, "four":4,"five":5}
>>> f = lambda x: x[1]
>>> my_dict.items()
dict_items([('one', 1), ('two', 2), ('three', 3), ('four', 4), ('five', 5)])
>>> [f(x) for x in my_dict.items()]
[1, 2, 3, 4, 5]
>>> my_dict.keys()
dict_keys(['one', 'two', 'three', 'four', 'five'])
>>> [f(x) for x in my_dict.keys()]
['n', 'w', 'h', 'o', 'i']
  • Related