Question

I spent my morning reading similar questions/answers (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?) but I'm still not able to solve the problem.

I have this tab dictionary with a tuple as key and I want as values: an integer, a dictionary, another dictionary and some lists. Then for every key, something like this: (str,str,str,str):{int, {}, {}, [], [] ...}

I want to be able to update these values structures and I need defaultdict because I don't know all the keys and anyway they are too much to be declared one by one manually.

I'm able to do this for a structure like this (str,str,str,str):{int} in this way:

tab=defaultdict(lambda: defaultdict(int))

tab[key][0]+=1

Or for a structure like this (str,str,str,str):{{}, {}} in this way:

tab=defaultdict(lambda: defaultdict(lambda: defaultdict(int)))

tab[key][1][str]+=1

tab[key][2][str]+=1

But not for what I really need. Thank you!

Ok, thank to @RemcoGerlich I'm trying to fix the problem, but I never used class before and maybe there's still something wrong in my code... Btw the int is a counter, the two dictionary have ip addresses like keys and the number of occurrences as values.

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)
Was it helpful?

Solution

I would create a class for your values, it's obviously complicated.

class YourClass(object):
    def __init__(self, anint=0, adict=None, anotherdict=None, somelists=None):
        self.anint = anint
        self.adict = adict if adict is not None else {}
        self.anotherdict = anotherdict if anotherdict is not None else {}
        self.somelists = somelists if somelists is not None else []

(don't use {} or [] as default arguments, that leads to them being shared between all instances).

Then you can use a defaultdict(YourClass) and also set things like tab[key].anotherdict[str] ...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top