Created
October 8, 2025 03:26
-
-
Save ggmartins/6aae94b143983c76a3830c2462be9927 to your computer and use it in GitHub Desktop.
unique list SortedDict vs dict vs in
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # /// script | |
| # requires-python = ">=3.13" | |
| # dependencies = [ | |
| # "sortedcontainers", | |
| # ] | |
| # /// | |
| from timeit import timeit | |
| import random | |
| from functools import reduce | |
| from sortedcontainers import SortedDict | |
| data = [random.randint(1,1000) for i in range(10000)] | |
| def unique_in_orderX(d): | |
| r = SortedDict() | |
| result = list(reduce(lambda acc, x: (acc if x in acc else acc.__setitem__(x, 0) or acc ) , d, r).keys()) | |
| print(f"{unique_in_orderX.__name__} = {result[:10]}...") | |
| def unique_in_orderY(d): | |
| r = {} | |
| result = list(reduce(lambda acc, x: (acc if x in acc else acc.__setitem__(x, 0) or acc ) , d, r).keys()) | |
| print(f"{unique_in_orderY.__name__} = {result[:10]}...") | |
| def unique_in_orderZ(d): | |
| r = SortedDict() | |
| result = list(reduce(lambda acc, x: (acc.__setitem__(x, 0) or acc ) , d, r).keys()) | |
| print(f"{unique_in_orderZ.__name__} = {result[:10]}...") | |
| def unique_in_orderW(d): | |
| result = reduce(lambda acc, x: acc if (acc and acc[-1] == x) or (x in acc) else acc + [x], d, []) | |
| print(f"{unique_in_orderW.__name__} = {result[:10]}...") | |
| print(timeit(lambda x=data: unique_in_orderX(data), number=5)) | |
| print(timeit(lambda x=data: unique_in_orderY(data), number=5)) | |
| print(timeit(lambda x=data: unique_in_orderZ(data), number=5)) | |
| print(timeit(lambda x=data: unique_in_orderW(data), number=5)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment