Now that Python 3.7 makes order-preserving dicts officially part of the language spec instead of an implementation detail, I've been trying to wrap my head around how best to use this property. Today, I've found I needed an order preserving set and think the dictionary might do the trick.
Suppose we have a list of hashable element. We want a list of unique entries and we want to keep the order of these entries based on first appearance. A simple dictionary constructor should do the trick:
ls = "Beautiful is better than ugly. Explicit..."
uniques = list({s:0 for s in ls})
>>> ['B', 'e', 'a', 'u', 't', 'i', 'f', 'l', ' ', 's', 'b', 'r', 'h', 'n', 'g', 'y', '.', 'E', 'x', 'p', 'c']
This will preserve the ordering by first appearance and get rid of all duplicates.
I'd like to know what the community thinks of this use case and the order preserving feature in general.
Reading through the Zen of Python, I am conflicted. The method is simple but relies on implicit ordering.
Please let me know what you think. Thank you.
This approach of using a Python 3.7 dictionary as an order-preserving de-dupe is vetted by a core Python developer here. You can't really get a better recommendation than that.
Is there any reason this method shouldn't be used?
No.
Are there better ways to solve this problem?
No.
Is this method Pythonic?
Yes.
The method is simple but relies on implicit ordering.
Your question is tagged python-3.7. Dictionaries preserving insertion order is guaranteed, so there is not an implicit ordering here.
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