StormsEdge
StormsEdge

Reputation: 885

Lambda Function with Sorted in Python 3x

I've seen similar questions and answers on SO, but i'm struggling to understand how to apply it.

I am trying to port the following Python 2x code to Python 3x:

deals = sorted([DealData(deal) for deal in deals],
                lambda f1, f2: f1.json_data['time'] > f2.json_data['time]

I've seen suggestions to use the cmp_to_key function, but i can't get it working. What am I missing?

This is my attempt with CMP_to_key:

deals = sorted(DealData, key=functools.cmp_to_key(cmp=compare_timestamps))


def compare_timestamps(x,y):
    return x.json_data['timeStamp'] > y.json_data['timeStamp']

I receive the following error: cmp_to_key() missing required argument 'mycmp'(pos1)

Upvotes: 0

Views: 203

Answers (1)

Andrew
Andrew

Reputation: 396

For sorted in python 3 you need to tell it what key in the object to use for sorting

deals = sorted(
    [DealData(deal) for deal in deals],
    key=lambda deal_data: deal_data.json_data["time"]
)

cmp_to_key is only needed if you had an existing comparison function ie:

from functools import cmp_to_key

def compare_deals(d1, d2):
    if d1.json_data["time"] > d2.json_data["time"]:
        return 1
    if d1.json_data["time"] < d2.json_data["time"]:
        return -1
    # equal
    return 0

deal = sorted(
    [DealData(deal) for deal in deals],
    key=cmp_to_key(compare_deals)
)

The Sorting How To in the python documentation gives more examples.

Upvotes: 2

Related Questions