I have a lists of integers that I would like to use as keys in python dictionaries. I'm caching results from a function(s) that takes a list of ints as input. My current solution:
list_of_ints = [1,20,3,4]
key = str(sorted(list_of_ints))[1:-1].replace(' ','')
which generates the key '1,3,4,20'. Seems like there should be a faster/prettier/more-pythonic way to do this.
Just use a tuple as a key. Tuples are immutable and hashable, so they're useful as dictionary keys.
Notably they DO care about order, so
[1, 20, 3, 4]
won't produce the same value as[1, 3, 20, 4]
You could even create a container that does this for you.
Don't try to serialize it yourself. If you do, don't use string manipulation -- it's too ugly. If you are sincerely memory starved or you have hundreds of thousands of these records, you could save insignificant space by serializing like:
which should give you a unique (incredibly large!) integer to store that will be smaller in memory than the tuple. Don't do this if you can avoid it -- it's very opaque.
In the comments you mention you will not have duplicate values in the key, so
frozenset
is definitely what you're looking for.frozenset
objects are immutable hashableset
-like objects. They are order-agnostic and ignore duplicates.You also can create hashable list.