How to do "GROUP BY" mathematically?
I have a data structure of key value pairs and I want to implement "GROUP BY" value.
Both keys and values are strings.

So what I did was I gave every value(string) a unique "prime number", then for every key I stored the multiplication of all the prime numbers associated with different values that a particular key have.
So if key "Anirudh" has values "x","y","z" then I store the number M(Key) =  2*3*5 = 30 as well.
Later if I want to do group by a particular value "x"(say) then I just iterate over all the keys, and divide the M(key) by the prime number associated with "x". I check if the remainder is 0. If it is zero then that particular "key" is a part of group by for valuer "x".

I know that this is the most weird way to do it. Some people sort the key value pairs(sorted by values). I could have also created another table(hash table) already grouped by "values". So I want to know a better method than mine (there must be many). In my method as the number of unique values for a particular key increases the product of prime number also increases (that too exponentially). 

Thanks in advance for helping me out.


How to do "GROUP BY" mathematically?
===

I have a data structure of key value pairs and I want to implement "GROUP BY" value.
Both keys and values are strings.

So what I did was I gave every value(string) a unique "prime number", then for every key I stored the multiplication of all the prime numbers associated with different values that a particular key have.
So if key "Anirudh" has values "x","y","z" then I store the number M(Key) =  2*3*5 = 30 as well.
Later if I want to do group by a particular value "x"(say) then I just iterate over all the keys, and divide the M(key) by the prime number associated with "x". I check if the remainder is 0. If it is zero then that particular "key" is a part of group by for valuer "x".

I know that this is the most weird way to do it. Some people sort the key value pairs(sorted by values). I could have also created another table(hash table) already grouped by "values". So I want to know a better method than mine (there must be many). In my method as the number of unique values for a particular key increases the product of prime number also increases (that too exponentially). 

Thanks in advance for helping me out.

