【发布时间】:2013-12-30 22:01:44
【问题描述】:
我花了一上午的时间阅读类似的问题/答案(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?),但我仍然无法解决问题。
我有这个以元组作为键的选项卡字典,我想要作为值:一个整数、一个字典、另一个字典和一些列表。然后对于每个键,像这样:(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)
【问题讨论】:
-
我在这里没有看到多级字典... :(
-
更改它,以便在 init 中将它们初始化为 defaultdict(int) 而不是 {}(编辑:int 而不是 0...)
标签: python dictionary nested defaultdict