M
M
maryaturova2021-12-31 00:02:50
Python
maryaturova, 2021-12-31 00:02:50

Sort dictionary by multiple values ​​with condition on time.time()?

Dear!
I need to sort a dictionary by several values ​​('loss' and 'average_time') with the condition that "status"= False and "next_time" is less than time.time().

obj = {    
        "key-1": {
            "loss": 0,
            "next_time": 1640891811,
            "status": False,
            "average_time":0
        },  
        "key-2": {
            "loss": 1,
            "next_time": 1640891830,
            "status": True,
            "average_time":0
        },  
        "key-3": {
            "loss": 1,
            "next_time": 1650891843,
            "status": False,
            "average_time":0
        }
    }
sort_arr = sorted(obj, key=lambda x: (obj[x]['loss'], obj[x]['average_time']))

Of course, you can first create a new dictionary and add it by enumeration according to these conditions, and then sorted .
But I still hope there is an easier solution.
Thanks!!!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2021-12-31
@Vindicar

Well, firstly, ordinary dictionaries are not particularly amenable to sorting. The order of enumeration of keys in the dictionary is not defined, if I'm not confused - there is no guarantee that on different machines, or on different versions of python, or even on different script runs, the order will be the same.
There is, however, collections.OrderedDict - here they remember the order of the keys, but this order is always chronological - the latest given key will always be the last one in the enumeration.
Secondly, better decompose the task into two. First filter what you need, then sort. Doing everything in one pass is difficult, and is it necessary?
In general, I would advise temporarily presenting a dictionary as a list of tuples (key, value), and filter / sort this list.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question