0

I'm trying to get an ordered set in Python 3.8. According to this answer, I'm using dict.fromkeys() method to get the unique items from a list preserving the insertion order. What's the time complexity of this method? As I'm using this frequently in my codebase, is it the most efficient way or is there any better way to get an ordered set?

>>> lst = [4,2,4,5,6,2]
>>> dict.fromkeys(lst)
{4: None, 2: None, 5: None, 6: None}
>>> list(dict.fromkeys(lst))
[4, 2, 5, 6]
  • 2
    [Python complexity cheat sheet](https://www.geeksforgeeks.org/complexity-cheat-sheet-for-python-operations/) – Barmar Feb 02 '23 at 17:30
  • 1
    Inserting into a dictionary is amortized O(1). Iterating over the list is O(n). – Barmar Feb 02 '23 at 17:31
  • 2
    I suspect this is the best you can do. `dict.fromkeys()` should be implemented in optimized C code, so any loop in Python is likely to be worse. – Barmar Feb 02 '23 at 17:33

0 Answers0