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)
cmp_to_key? Please show us your code so that we can tell you what you might be missing.keyvariable to thesortedfunction 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 ofDealDataand 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