1

I was trying to use the orderedDict module to sort my dictionary but came up with this question while looking at some example code like below:

# regular unsorted dictionary
d = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2}

# dictionary sorted by key
OrderedDict(sorted(d.items(), key=lambda t: t[0]))
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])

# dictionary sorted by value
OrderedDict(sorted(d.items(), key=lambda t: t[1]))
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])

So what confused me in the code is the Lambda function used inside sorted() function. I understand that 't' is the argument and 't[0]' or 't[1]' are the expression but can't figure out how 't' get assigned value inside the sorted(). In the code it seems like 't = d.items()' happens automatically?

Please help me to understand the mechanism here and thanks a lot in advance!

Diego
  • 13
  • 3
  • Because `sorted` calls the function with every value in the iterable you pass to `sorted` – juanpa.arrivillaga Sep 27 '18 at 16:14
  • Related: [What exactly are iterator, iterable, and iteration?](https://stackoverflow.com/questions/9884132/what-exactly-are-iterator-iterable-and-iteration) – pault Sep 27 '18 at 16:15

1 Answers1

1

First of all, note that a lambda is a convenient way to define a regular function like any other. This code:

sorted(d.items(), key=lambda t: t[0])

is functionally equivalent to this one:

def get_first(t):
    return t[0]

sorted(d.items(), key=get_first)

You are passing a function to sorted (not the result of calling it). sorted takes that function and passes a value to it whenever it needs to.

For example, sorted could be naïvely defined like this:

def sorted(original_values, KEY):
    values = list(original_values)  # create a copy
    n = len(values)
    for j in range(n):
        for k in range(n - 1):
            if KEY(values[k]) > KEY(values[k + 1]):  # <----------
                values[k], values[k + 1] = values[k + 1], values[k]
    return values

The KEY parameter is a function that is used in the line with the arrow to compare two values to see if they need to be exchanged.

Roberto Bonvallet
  • 31,943
  • 5
  • 40
  • 57
  • 'sorted takes that function and passes a value to it whenever it needs to' this is the part I don't understand... Does it just happen behind the scene and we really don't need to know how that work? I am using Python for data analytics. – Diego Sep 27 '18 at 16:27
  • Just being a grammar hound maybe, but lambda isn't "completely" the same. 'Similair' yes, exactly the same especially in scope.. no – Jab Sep 27 '18 at 16:28
  • @Diego yes, `sorted` takes care of everything. – Roberto Bonvallet Sep 27 '18 at 16:32
  • @Jaba Yes, I changed "completely equivalent" to "functionally equivalent" to not imply that's exactly the same. – Roberto Bonvallet Sep 27 '18 at 16:34
  • @RobertoBonvallet The example code of sorted function helps me understand it now! I was actually trying to find the source code of sorted function... Anyway, thanks a lot for answering my question! – Diego Sep 27 '18 at 16:37
  • Haha, thanks @RobertoBonvallet, you had my mind racing! – Jab Sep 27 '18 at 16:48
  • Probably good to note, in actuality, the key function is called exactly once for ever element in the iterable. So, in essence, the key function is [used to implement the so-called Schwartzian transform](https://docs.python.org/3/howto/sorting.html#the-old-way-using-decorate-sort-undecorate) – juanpa.arrivillaga Sep 27 '18 at 17:25
  • @Jaba what do you mean not the same in scope? – juanpa.arrivillaga Sep 27 '18 at 17:25