0

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)

5
  • How are you using cmp_to_key? Please show us your code so that we can tell you what you might be missing. Commented May 7, 2020 at 15:14
  • What you need to understand is the key variable to the sorted function assumes it is given two instances of items in the list. You then decide what is the function you want to compare them by. So in your example, it receives two instances of DealData and you need to do some comparison between f1 and f2 in some manner (i.e. compare between a specific class attribute/property). Note that if your class is what we call "comparable", then it's usually better to implement the comparison functions (__lt__, __eq__` etc..) in the class itself Commented May 7, 2020 at 15:18
  • @blhsing Added Attempt Commented May 7, 2020 at 15:36
  • @Zionsof There are just properties and such implemented in the class. Specifically, i'm accessing the json_data['timeStamp'] field. Does this change anything? Commented May 7, 2020 at 15:43
  • Yeah but in your attempt you return a boolean value of True or False. What you need to do is return some number to indicate which one is lower. @Andrew gave a good example and some links to follow up to that Commented May 10, 2020 at 10:50

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.