I have a dictionary in python3 where I define priorities for a particular set of tasks:
labels_priority = {"laundry":4, "cooking":4, "cutting_grass":3, "cleaning":0, "paint":0, "vacuuming":0, "pealing":1, "dishes":2}
These are all the tasks in general.
Now I get an external list which shows that I have to do these tasks on a given day:
tasks_to_do_today = [cleaning, dishes, vacuuming, cooking]
I want to do these tasks using a for loop but my question is how do I make sure the order is correct?
I want to get a list ordered as such based on list being compared to the dictionary and priority order:
cleaning
vacuuming
dishes
cooking
Notice how "cleaning" and "vacuuming" were 0 priority so they come first. I am also noticing that python removes duplicates, that is something that I don't want. Please advise.
Also, If there is a better solution than what I'm trying to implement please let me know.
CodePudding user response:
You can use the key
argument of list.sort
to alter what your sort order is using to determine precedence:
labels_priority = {"laundry":4, "cooking":4, "cutting_grass":3, "cleaning":0,
"paint":0, "vacuuming":0, "pealing":1, "dishes":2}
tasks_to_do_today = ["cleaning", "dishes", "vacuuming", "cooking"]
tasks_to_do_today.sort(key=labels_priority.__getitem__)
If you want some sort of default priority for unrecognized tasks, you can change the key
to a simple lambda
:
tasks_to_do_today.sort(key=lambda x: labels_priority.get(x, 1000))
or the like, which means if the key is not found, instead of dying loudly with a KeyError
, it silently assigns it a priority of 1000
.
This sorts that string as if it had the associated numeric value from labels_priority
. When there's a tie, Python's sort algorithm is stable, so two strings with the same priority will appear in the same order they appeared in the original list
(e.g. in this case, "cleaning"
sorts before "vacuuming"
). You could conceivably add a tie-breaker (by having the key
function return a tuple
, where the first element is the most important comparison, and each one after that serves as a fallback comparison), but there's no indication you need that here.
CodePudding user response:
Try to start from this:
tasks_to_do_today = ["cleaning", "dishes", "vacuuming", "cooking"]
print(sorted(tasks_to_do_today, key=lambda x: labels_priority[x]))
Python removes duplicates in a dictionary, not in a list.
Upd. Thanks @shadowranger for clarification.