I made a list of lists of possible combinations of n length from a list of items, and now I want to create a dictionary where each key is one of the items from list of lists of possible combinations, so I can start counting how many times each combination occurs in a set of observations (early stages of programming an association rules engine). Here's what I have:
import itertools
stuff=(1,2,3,4)
n=1
combs=list()
while n<=len(stuff):
combs.append(list(itertools.combinations(stuff,n)))
n = n+1
print combs
viewers={'Jim':(1,3,4), 'Bob':(1,2,4), 'Jerry':(1,4), 'Ben':(2), 'Sal':(1,4)}
showcount={}
for list in combs:
for item in list:
showcount["%s",%(item)]=0
print viewers
print showcount
How do I get the item to appear as the key in the dictionary? So for example, I'd like the combination '(1,2,4):0' to be a key value pair so I can later count the number of times '(1,2,4)' appears. I'm pretty new to Python, but I did seach around for an answer and couldn't find one. Apologies if this has been answered and I just couldn't find it.
解决方案
You can use tuples as keys:
mydict = { (1, 2, 4): 0 }
If you want to count things, take a look at collections.Counter, it makes counting trivial, no need to initialize the keys to 0:
counts = collections.Counter()
counts[(1, 2, 4)] += 1