Suppose I have a dictionary/list/anything. I am sorting this set according to some function (not directly dependent on the value, square is given as an example):
dict_a = {('a', 3), ('b', 2), ('c', 1)}
def temp(x):
return x**2
print(sorted(dict_a, key=lambda item:temp(item[1])))
Is there any way/syntax to get/return the value of the key obtained from a call to lambda (by which the resulting list was sorted), in order not to calculate it twice later, e.g.:
[(1, ('c', 1)), (4, ('b', 2)), (9, ('a', 3))]
rather than
[('c', 1), ('b', 2), ('a', 3)]
Preferably in a single line of code and only standard libraries. Does Python have capability to do that? Thanks!
CodePudding user response:
You could already map
it before sorting:
>>> sorted(map(lambda x: (temp(x[1]), x), dict_a))
[(1, ('c', 1)), (4, ('b', 2)), (9, ('a', 3))]
>>>
Or with a list comprehension:
>>> sorted([(temp(x[1]), x) for x in dict_a])
[(1, ('c', 1)), (4, ('b', 2)), (9, ('a', 3))]
>>>
CodePudding user response:
Just do the transform beforehand and sort that:
dict_a = {('a', 3), ('b', 2), ('c', 1)}
def temp(x):
return x**2
expected = [(1, ('c', 1)), (4, ('b', 2)), (9, ('a', 3))]
transformed = [(temp(item[1]), item) for item in dict_a]
assert sorted(transformed) == expected
Note that you typoed ('c', 3)
in your question and that dict_a
is not a dict, but a set of tuples..