0

I am trying to implement the Apriori algorithm... http://codeding.com/articles/apriori-algorithm in Python.

The highest level data structuring goes something like this:

frequentItemSets[ k-level : itemSetDictionary]
                            |
                            |__
                               itemSetDictionary[ listOfItems : supportValueOfItems]
                                                  |
                                                  |__
                                                     list of integers, sorted lexicographically

I need to keep track of an arbitrary number of sets, the cardinality (k-level) of those sets, and a value that I calculate for each of those sets. I thought that using a list for all of the sets would be a good idea as they maintain order and are iterable. I tried to use lists as the keys within the itemSetDictionary, as you can see above, but now I see that iterable data structures are not allowed to be keys wihtin Python dictionaries.

I am trying to figure out the quickest way to fix this issue. I know that I can just create some classes so that the keys are now objects, and not iterable data structures, but I feel like that would take a lot of time for me to change.

Any ideas?

Gthoma2
  • 687
  • 1
  • 9
  • 22

1 Answers1

2

Dictionary keys must be hashable, which usable requires them to be immutable. Whether they are iterable is immaterial.

In this particular case, you probably want to use frozensets as keys.

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • I see that Tuples are immutable and are ordered, I imagine tuples would work? I need the item sets to provide an order to their elements. – Gthoma2 Feb 02 '14 at 22:11
  • @Gthoma2: Yes, tuples would work as well, also e.g. tuples of frozensets. – Sven Marnach Feb 02 '14 at 22:11
  • tuples only work to the extent that they also contain immutable data structures. i.e., `(({1,2},{3,4}))` still cannot be used as a key, even though it is a tuple, since the tuple contains mutable sets. – dawg Feb 04 '14 at 03:27
  • Yes -- you can use a frozen set. You can also do `str({ ur set })` and use the string of the set as a key since strings are hashable. – dawg Feb 04 '14 at 03:29