Python dictionary sort list with null values ββat the end
I have a homogeneous list of null-valued dictionaries, but it can contain any value types. Example:
values=[{'buy_qty': 15, 'product_id': 30}, {'buy_qty': 0,'product_id': 33},{'buy_qty': 25, 'product_id': 50}, {'buy_qty': 7, 'product_id': 22}]
Is there a way, without reinventing the wheel, to get the list sorted by the "minimum" buy_qty "usually for the python path, but the" null "values ββat the end of the list, for example:
values=[{'buy_qty': 7, 'product_id': 22}, {'buy_qty': 15, 'product_id': 30}, {'buy_qty': 25, 'product_id': 50}, {'buy_qty': 0,'product_id': 33}]
I tried with itemgetter,
sorted(total_lines, key=itemgetter('buy_qty'))
It seems to me that there might be some trick here with the "key" parameter
You are correct about the key function. I added a key function that sorts by buy_qty, except it is at most zero, and then treats it like infinity, essentially moving it to the end.
sorted(values, key = lambda x: x['buy_qty'] if x['buy_qty'] > 0 else float('inf'))
You can define any function to be used for sorting - either outside sorted
or inside using lambda. This way you can make exceptions (in this case for count 0)
sorted(values, key=lambda x: x['buy_qty'] if x['buy_qty'] > 0 else float('Inf'))
Use a custom compare function.
def custom_comparator(item1, item2):
if item1 == item2:
return 0
elif 0 < item1 < item2 or item2 == 0:
return -1
else:
return 1
sorted(total_lines, cmp=custom_comparator, key=itemgetter('buy_qty'))