Search code examples
pythonpython-2.7dictionaryhashable

Tried to implement lists as dictionary keys within algorithm, what's a quick solution?


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?


Solution

  • 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.