0

To sort a dictionary on values, all the answers I found use a lambda. Is it possible to use a function? I can't seem to get the values passed correctly.

sales = {
    'north': 2,
    'south': 6,
    'east': 8,
    'west': 7,
}

def get_value(collection,key):    # substitue for lambda x: x[1]
    return collection.get(key)

print(sales)
#sort_sales = sorted(sales.items(), key=lambda x: x[1])   # uses lambda
sort_sales = sorted(sales.items(), get_value( sales,sales.items() ) )
print(sort_sales)

2 Answers 2

2

Have a look at what sales.items() gives you. Based on that you can do:

def get_value(item):
    return item[1]

sorted(sales.items(), key=get_value)

Returns

[('north', 2), ('south', 6), ('west', 7), ('east', 8)]
Sign up to request clarification or add additional context in comments.

2 Comments

Wow, it snapped into focus. I didn't understand what sales.items actually returned. And that makes the [1] in the function clear. Thanks.
Instead of defining your own get_value, you can also use operator.itemgetter(1): docs.python.org/3/library/operator.html#operator.itemgetter
2

The equivalent of lambda x: x[1] is

def get_value(x):
    return x[1]

Generally, you can turn the lambda argument list into a function argument list and the lambda expression into a return statement, and that will suffice for any non-capturing lambda. For capturing lambdas, you'll need to make a nested function that explicitly captures the variables you want.

# (Non-specific example)
def get_value(foo):
    def _function(x):
        return x[foo]

# If we assume we have a variable foo defined as
foo = 1

# Then the two are roughly equivalent
fn1 = get_value(foo)
fn2 = lambda x: x[foo]

1 Comment

Thanks, Silvio, for breaking that down. For some reason I was stumped on why [1] thinking it had to do with the first-most in the sorted order. And I didn't see how it changed to 2nd. It is the 1th value in each element of the collection.items() list.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.