0

I'm quite new with python and I've question to ask about lambda. I had dictionary which was needed to print sorted as by it's values.

def print_in_accordance_of_values(english_spanish):
    for value, key in sorted(english_spanish.items(), key = lambda value: value[1]):
        print(key, value)

def main():
    english_spanish = {"hi": "hola", "thanks": "gracias", "yes": "si", "no": "no"}
    print_in_accordance_of_values(english_spanish)

main()

What actually happens in this part of the code:

for value, key in sorted(english_spanish.items(), key = lambda value: value[1]):

Thank you for your answers!

Mkk0
  • 25
  • 4
  • Possible duplicate of [Syntax behind sorted(key=lambda :)](https://stackoverflow.com/questions/8966538/syntax-behind-sortedkey-lambda) – SiHa Oct 13 '17 at 13:20
  • BTW, it's more efficient to _not_ use a `lambda` function. Instead, you should use `itemgetter` from the standard `operator` module for this. Eg, `key=operator.itemgetter(1)` – PM 2Ring Oct 13 '17 at 13:26

1 Answers1

0

Let's concentrate on the part sorted(english_spanish.items(), key = lambda value: value[1]), because that's what your question is about. The generator (think of it as a list in this case) english_spanish.items() yields the pairs:

('hi', 'hola')
('thanks', 'gracias')

and so on. To get them sorted, the sorted function needs to know how to. The key word lambda creates a little anonymous function which gets the pairs (as value) and yields the second entry of each pair. This is what sorted takes as a key to sort upon.

elzell
  • 2,228
  • 1
  • 16
  • 26