简体   繁体   中英

What is the optimal way to sort a list of dictionaries based on multiple keys and remove some of the dictionaries

What is the optimal(time) way to sort a list of dictionaries based on multiple keys and at the same time removing some of the dictionaries from the output?

I want the output to be a list of all dictionaries where "protected":0 and sorted by an arbitrary number of other keys.

Data

[{"raffle_id":"81","created":"2013-01-07 19:47:57","instant":"1","protected":0,"expire":"never","ticket_price":"0.00050000",
"tickets_total":"10","tickets_sold":"1","my_tickets_count":"1"},
{"raffle_id":"83","created":"2013-01-07 19:49:20","instant":"0","protected":1,"expire":"4d 23h 59m","ticket_price":"0.01000000",
"tickets_total":"50","tickets_sold":"0","my_tickets_count":"0"}]

Current method

raffle_list = [raffle for raffle in raffle_list if raffle("protected") == "0"]

sorted_raffles = sorted(raffles_list, key = operator.itemgetter("ticket_price", "tickets_sold", "my_tickets_count", "tickets_total"))

All i can suggest is making raffle_list a generator but that may/may not be faster depending on the data and memory available. eg. list comps are faster for small data sets but a generator avoids making a copy in memory, which may improve speed for huge data sets since sorted makes a copy as well:

(raffle for raffle in raffle_list if raffle("protected") == "0")

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