我花了早上阅读类似的问题/答案(What is the best way to implement nested dictionaries?,Multiple levels of keys and values in Python,Python: How to update value of key value pair in nested dictionary?),但我仍然无法解决问题。多级字典python
我有这个选项卡字典与元组作为关键,我希望作为值:整数,字典,另一个字典和一些列表。然后对于每个键,如下所示:(str,str,str,str):{int,{},{},[],[] ...}
我希望能够更新这些值结构,我需要defaultdict,因为我不知道所有的键,反正他们太多,不能手动一个一个地宣布。
我能够像这样的结构做到这一点(STR,STR,STR,STR):{} INT这样:
tab=defaultdict(lambda: defaultdict(int))
tab[key][0]+=1
为公结构是这样的(STR,STR,STR,STR):{{},{}}这样:
tab=defaultdict(lambda: defaultdict(lambda: defaultdict(int)))
tab[key][1][str]+=1
tab[key][2][str]+=1
但不适合我真正需要的。 谢谢!
好的,感谢@RemcoGerlich我试图解决这个问题,但我从来没有用过类,也许在我的代码中仍然有问题......顺便说一句int是一个计数器,两个字典都有IP地址像键和出现次数作为值。
class flux(object):
def __init__(self, count_flux=0, ip_c_dict=None, ip_s_dict=None):
self.count_flux = count_flux
self.ip_c_dict = ip_c_dict if ip_c_dict is not None else {}
self.ip_s_dict = ip_s_dict if ip_s_dict is not None else {}
def log_to_dict(dir_file,dictionary):
f = gzip.open(dir_file,'r')
for line in f:
line = line.strip('\n')
if not line: break
elements = line.split(" ")
key=elements[40],elements[18],elements[41],elements[37]
dictionary[key].count_flux+=1
dictionary[key].ip_c_dict[elements[0]]+=1
dictionary[key].ip_s_dict[elements[19]]+=1
###Main
tab=defaultdict(flux)
log_to_dict('/home/-/-.txt',tab)
我没有在这里看到一个多层次的字典都... :( – thefourtheye
变化它使得它们在__init__(编辑:int而不是0 ...)中被初始化为defaultdict(int)而不是{} – RemcoGerlich