Python – If we don’t have a key, how can we create a key that identifies a set of numbers in order to retrieve a set in a collection?

If we don’t have a key, how can we create a key that identifies a set of numbers in order to retrieve a set in a collection?… here is a solution to the problem.

If we don’t have a key, how can we create a key that identifies a set of numbers in order to retrieve a set in a collection?

I have several sets of numbers. I want to store these collections in a dictionary. I don’t know how to generate a key that uniquely identifies a collection. If I have a collection without a key, I want to automatically generate a key for that collection and check if the generated key is in the dictionary.

Solution

You can use frozenset as the dictionary key:

d = {frozenset([1, 2, 3]): 'a', frozenset([4, 5, 6]): 'b'}
print(d[frozenset([1, 2, 3])])  # 'a'

Related Problems and Solutions