Given a list of strings, I want to sort it alphabetically and remove duplicates. I know I can do this:
from sets import Set [...] myHash = Set(myList)
but I don't know how to retrieve the list members from the hash in alphabetical order.
I'm not married to the hash, so any way to accomplish this will work. Also, performance is not an issue, so I'd prefer a solution that is expressed in code clearly to a fast but more opaque one.
fromkeys(list)) that goes through two phases: (1) Convert the list to a dict using the dict. fromkeys() function with the list elements as keys and None as dict values. (2) Convert the dictionary back to a list using the list() constructor. As dictionaries preserve the order of the keys, the list ordering is preserved.
A list can be sorted and deduplicated using built-in functions:
myList = sorted(set(myList))
set
is a built-in function for Python >= 2.3sorted
is a built-in function for Python >= 2.4If 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