Search code examples
pythondictionarycollectionscountpython-collections

Python: Creating a dictionary with key as a set and value as its count


I an implementing a Data Mining algo. I which my smallest object is a set. A set may contain a single item or multiple items (Itemset). I need to count the occurrences of such sets in a dictionary as :

Dict={set([<some items>] : count)}

I need such a data type for the following reasons:

  1. Order of items in a set is not considered (item1,item2,item3 same as item2,item3,item1 and so on...)
  2. Adding a set to a dictionary would avoid repeating of keys.
  3. Store the count in the same data structure along with the itemset.

Can you please suggest a simplest way of achieving this in python.


Solution

  • You could use Counter with frozenset as keys:

    from collections import Counter
    
    items = [
        [1, 2, 3],
        [1, 2],
        [3, 2, 1]
    ]
    
    c = Counter(frozenset(x) for x in items)
    print(c) # Counter({frozenset([1, 2, 3]): 2, frozenset([1, 2]): 1})