python - 多级字典python

标签 python dictionary nested defaultdict

我花了一上午的时间阅读类似的问题/答案( What is the best way to implement nested dictionaries?Multiple levels of keys and values in PythonPython: 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[键][0]+=1

或者对于像这样的结构 (str,str,str,str):{{}, {}} 这样:

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

tab[键][1][str]+=1

tab[键][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)

最佳答案

我会为你的值(value)观创建一个类,这显然很复杂。

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 []

(不要使用 {} 或 [] 作为默认参数,这会导致它们在所有实例之间共享)。

然后你可以使用 defaultdict(YourClass) 并设置诸如 tab[key].anotherdict[str] ...之类的东西

关于python - 多级字典python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20544411/

相关文章:

java - 使用嵌套的 for 循环检查数字是否为素数;如果是这样,将它们添加到集合中——不使用 isPrime 方法

python - pip install - 由对等方重置连接

dictionary - erlang dict的时间复杂度

c++ - 选择容器以插入多个数据库记录

python - 使用另一个列表作为 "filter"对 python 中的字典列表进行排序?

elasticsearch - 无论字段的位置如何,都在嵌套文档中搜索字段

python - 用类创建对象,为什么需要__init__(self, args) :?

python - Gunicorn 和主管背后的 Flask - 记录所有请求和响应

python - django 中的 _lte、__name、__startswith 等查询 - 记录在哪里?

python - 从两个 csv 文件创建嵌套字典