I am trying to sort a python list of strings. I know that I can use the method sorted and set the attribute key to be a function that implements the behavior I need to sort the elements of the dictionary on. My problem is that this method needs an argument.
UPDATE: I want the method to generalize to multiple arguments.
Example: I want to sort a list of strings based on their priorities in 2 dictionaries . So I need to use those priority dictionaries in sorting the list.
I want something like:
sorted(myList, key=sortingAlgorithm(priorityDictionary1, priorityDictionary2), reverse=True)
This can be done if I set the priority dictionaries as global variables and then I will not need to have it as an argument to the sorting algorithm. But, I want to be able to do it without global variables.
If this is not possible, can you please recommend the pythonic way of doing this.
Thanks in advance.
Try key=priorityDictionary.get
get is a method on a dictionary that takes a key and returns a value, if one is found.
Edit: The above solution applies to a case of a single dict. Here is a generalization where values of priorityDict2 are keys for priorityDict1.
And, as Padriac Cunningham points out, you can use a lambda to sort using nested dicts:
output = sorted(myList, key=lambda element: priorityDict1[priorityDict2[element]])
Use a closure.
def something(foo):
def somethingsomething(bar):
return foo(bar)
return somethingsomething
baz = something(len)
print baz('quux')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With