简体   繁体   中英

Python sort list of dictionary with zero values at the end

I have homogeneous list of dictionary with zero values, but it can contain any type of values. 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 way without reinventing the wheel to get list sorted by 'minimum "buy_qty" usual for python way, but "zero" values at the end of the list, like that:

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 have tried with itemgetter,

sorted(total_lines, key=itemgetter('buy_qty'))

I feel like here can be some trick with "key" parameter

You're right about the key function. I added a key function that sorts by buy_qty, except if it's not greater than zero to then treat it as 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 use as sort - either outside of the sorted or inside using a lambda. That way, you can make exceptions (in this case for the 0 quantity)

 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'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM