简体   繁体   中英

Sorting a list based on two dictionaries

I have looked at different solutions for sorting dictionaries and got confused. Therefore, decided to ask my own here.

I am designing a queuing application that gives the priority to the people who did not participate before. After that, the priority goes to the time of the request.

Therefore, I have two dictionaries. One keeps track of the number of participation and the other keeps track of the time of participation.

On a press of a button, I am recording the time in my first dictionary as follow:

dictionary1[name] = time.time()

it will be as follow:

dictionary1 = {'jessi':time.time(), 'jack':time.time(), 'bob':time.time()}

The values of time.time() are float numbers. The second dictionary keeps track of how many participations as follow:

dictionary2 = {'jack':2 , 'john':1, 'sam': 4}

I want people with 0 participation to be at the top of the queue. After that, people with the less number of participation.

After sorting by participation, I want to sort people according to the time of submission.

I saw many examples using something like:

sorted_dict = sorted(dict['values'], key=lambda k: k['a']['b'])

However, I am getting errors when the value does not exist in dictionary 2.

out of those two dictionaries, I want to have a list ordered as per the above criteria. The list should be generated from dictionary1 but sorted according to values in dictionary1 and dictionary2.

How can I approach this?

EDIT:

Assuming that dictionary1 = {'jessi':10, 'jack':20, 'bob':30} dictionary2 = {'jessi':1, 'jack':2 , 'john':1, 'sam': 4} The output should be: list = ['bob','jessi','jack']

Bob is given first priority because he has no presence in dictionary 2.

You can sort it with a key function that returns a tuple of participation count and time:

import time
dictionary1 = {'jessi':time.time()+1, 'jack':time.time(), 'bob':time.time()-1}
dictionary2 = {'jack':2 , 'john':1, 'sam': 4}
print(sorted(dictionary1, key=lambda k: (dictionary2.get(k, 0), dictionary1[k])))

This outputs:

['bob', 'jessi', 'jack']

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