Python 如何定义多级字典结构并将数据插入其中?
我正在尝试使用defaultdict创建一个多级Python字典。字典的结构如下所示:Python 如何定义多级字典结构并将数据插入其中?,python,dictionary,Python,Dictionary,我正在尝试使用defaultdict创建一个多级Python字典。字典的结构如下所示: { "source1": { "gene": { "gene1": { "location": [ [ 10, 200 ]
{
"source1": {
"gene": {
"gene1": {
"location": [
[
10,
200
]
],
"mrna": {
"1": {
"location": [
[
10,
200
]
],
"product": "hypothetical",
"CDS": {
"location": [
[
10,
50
],
[
100,
200
]
]
}
}
}
}
}
}
}
但是在Python中的这种情况下,我们需要在插入任何数据之前定义结构
我尝试定义的结构是:
from collections import defaultdict
dct = defaultdict(lambda: defaultdict(lambda: defaultdict(lambda: defaultdict(
lambda: defaultdict(lambda: defaultdict(lambda: defaultdict(list)))))))
现在,为了在上面的结构中插入数据,我使用下面的代码来创建上面定义的格式
dct['source1']['gene']['gene1']['location'].append([10, 200])
dct['source1']['gene']['gene1']['mrna']['1']['location'].append(['10', '200'])
dct['source1']['gene']['gene1']['mrna']['1']['product'] = 'hypothetical'
dct['source1']['gene']['gene1']['mrna']['1']['CDS']['location'].append([10, 50])
dct['source1']['gene']['gene1']['mrna']['1']['CDS']['location'].append([100, 200])
但是我得到了一些错误。有人能帮我创建多级词典吗?子词典的构建可以自动完成:
>>> from collections import defaultdict
>>> f = lambda: defaultdict(f)
>>> d = f()
>>> d['usa']['texas'] = 'lone star'
>>> d['usa']['ohio'] = 'buckeye'
>>> d['canada']['alberta'] = 'flames'
在您的代码中,您试图获取dct[source1][gene][gene1][mrna][1][CDS][location],但没有CDS键,只有一张CDS。用CD更换CD Python键区分大小写,因此请确保与字符串完全匹配
此外,我建议不要像那样将数据放入超特定的dict中,因为这样调试和实际查看出错的地方会变得更加困难,比如区分大小写的cd。您的字典定义使用的是其他数据类型,而不是您要添加的数据类型- 由于您的拼写错误,请检查ChristianFigueroas Answare 如果我运行您的代码,我会得到错误AttributeError:'collections.defaultdict'对象没有属性'append'。这就是为什么我用正确的数据类型创建了您的字典,请原谅我使用字典而不是默认的dict dct={}Dict dct['source1']={}Dict dct['source1']['gene']={}Dict dct['source1']['gene']['gene1']={}Dict dct['source1']['gene']['gene1']['location']=[]列表 dct['source1']['gene']['gene1']['mrna']={}Dict dct['source1']['gene1']['mrna']['1']={}Dict dct['source1']['gene1']['mrna']['1']['location']=[]列表 dct['source1']['gene1']['mrna']['1']['product']=String dct['source1']['gene1']['mrna']['1']['CDS']={}Dict dct['source1']['gene1']['mrna']['1']['CDS']['location']=[]列表 dct['source1']['gene']['gene1']['location'].追加[10200] dct['source1']['gene1']['mrna']['1']['location'].追加['10','200'] dct['source1']['gene1']['mrna']['1']['product']='假想' dct['source1']['gene1']['mrna']['1']['CDS']['location'].追加[10,50] dct['source1']['gene1']['mrna']['1']['CDS']['location'].追加[100200]
我希望你能看到我在那里所做的。为了意识到你正在撞到墙,你必须用你的头撞上墙多少次?@alfasin-这是不可能的吗?当然可能,但你真的想维护代码,比如:dct['source1']['gene1']['mrna'['1']['CDS']['location'].append[100200]?是的,我想保持这种结构。基因gene1在实际数据集中是可变的。但为了更好地理解,我在这里只使用这两个名称祝你好运!谢谢你的帮助。但是上面的字典将无法保存任何列表。你能帮我吗。
dct["source1"]["gene"]["gene1"]["mrna"]["1"]["cds"]["location"].append( ... )