Key = lambda KV: KV[1]

Hi!

I’m working on a dictionary and there’s one line that I don’t understand:

character_frequency_sorted.sorted(
character_frequency.items(),
key=lambda kv: kv[1],
reverse=True

specifically I don’t understand the line: key=lambda kv: kv[1]

What does “lambda” do and what’s going on here?

If possible then please share an example!

Please keep in mind that I am a beginner.

Thank you very much!

Josh

A lambda is an anonymous function. It is that function that is selecting values at the given index.

I think it’s better to untangle this and just look at basic lambda functions. It’s always good to practice these things in the terminal or a text editor to see how they can be applied.

Simple example

test = [1,2,3,4]
key = lambda x: x[1]
# so what is key?
print(key)
# <function <lambda> at 0x7fafff8855f0>
# Ok! it's a function, let's treat it like one and give it a parameter
print(key(test))
# Output: 2
# So we can say
def key_2(some_list):
   return some_list[1]

print(key_2(test) == key(test))
# output: True

Note, this is a simple example, but the practicality of lambda functions in certain use-cases is very high, so play around to see what else it can do.

2 Likes

Thank you again Toastedpitabread!
This is a great example.

Respectfully,
Josh