具有可变深度的多级默认字典? [英] Multi-level defaultdict with variable depth?

查看:30
本文介绍了具有可变深度的多级默认字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很大的列表,例如:

I have a large list like:

[A][B1][C1]=1
[A][B1][C2]=2
[A][B2]=3
[D][E][F][G]=4

我想构建一个多级字典,例如:

I want to build a multi-level dict like:

A
--B1
-----C1=1
-----C2=1
--B2=3
D
--E
----F
------G=4

我知道如果我使用递归 defaultdict 我可以写 table[A][B1][C1]=1, table[A][B2]=2,但这仅在我对这些插入语句进行硬编码时才有效.

I know that if I use recursive defaultdict I can write table[A][B1][C1]=1, table[A][B2]=2, but this works only if I hardcode those insert statement.

在解析列表时,我不知道需要多少个 [] 来调用 table[key1][key2][...].

While parsing the list, I don't how many []'s I need beforehand to call table[key1][key2][...].

推荐答案

你甚至可以不用定义一个类:

You can do it without even defining a class:

from collections import defaultdict

nested_dict = lambda: defaultdict(nested_dict)
nest = nested_dict()

nest[0][1][2][3][4][5] = 6

这篇关于具有可变深度的多级默认字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆