使用变量名称键将项目添加到字典python [英] adding item to dictionary python with a variable name key
问题描述
我从项目列表中列出了n个长度的可能组合列表,现在我想创建一个字典,其中每个键都是可能组合列表中的一个项目,因此我可以开始计算每个组合在一组观测值中发生了多少次(对关联规则引擎进行编程的早期阶段).这是我所拥有的:
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
如何使该项目显示为字典中的键?因此,例如,我希望组合'(1,2,4):0'是一个键值对,以便以后可以计算'(1,2,4)'出现的次数.我对Python很陌生,但是我一直在寻找答案,却找不到答案.抱歉,我已经找不到了.
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 }
如果您想数数,请查看 collections.Counter
,它使计数变得微不足道,无需将键初始化为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
这篇关于使用变量名称键将项目添加到字典python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!