简体   繁体   English

使用变量名键将项目添加到字典python

[英]adding item to dictionary python with a variable name key

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). 我从项目列表中列出了n个长度的可能组合列表,现在我想创建一个字典,其中每个键都是可能组合列表中的一个项目,因此我可以开始计算多少次每个组合都发生在一组观察值中(对关联规则引擎进行编程的早期阶段)。 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. 因此,例如,我希望组合'(1,2,4):0'是一个键值对,以便以后可以计算'(1,2,4)'出现的次数。 I'm pretty new to Python, but I did seach around for an answer and couldn't find one. 我对Python来说还很陌生,但我一直在寻找答案,却找不到答案。 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: 如果要计数,请看一下collections.Counter ,它使计数变得微不足道,无需将键初始化为0:

counts = collections.Counter()
counts[(1, 2, 4)] += 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM