Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ordered dictionary as ordered set

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.

  • Is there any reason this method shouldn't be used?
  • Are there better ways to solve this problem?
  • Is this method Pythonic?

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.

like image 739
Nathaniel Rivera Saul Avatar asked Jul 03 '18 02:07

Nathaniel Rivera Saul


1 Answers

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.

like image 156
wim Avatar answered Sep 18 '22 15:09

wim