简体   繁体   English

在嵌套的 dict python 中附加一个 dict

[英]Append a dict in a nested dict python

I would like to have a dictionary appended with new dictionaries.我想要一本附有新词典的词典。

t = {}
t['bush_mod']={} # Toplevel
ana1 = {}
ana1['ana1_lin_001']={}
t['bush_mod'] = ana1 # Add below Toplevel

ana2 = {}
ana2['ana2_lin_001'] = {}
ana2['ana2_lin_002'] = {}

t['bush_mod'] = ana2 # Add below Toplevel

When I add ana2 the dictionary t gets overwritten which i do not want.当我添加ana2 ,字典t被我不想要的覆盖。

OUT: {'bush_mod': {'ana2_lin_001': {}, 'ana2_lin_002': {}}}

I wanted to have ana2 as the second dict (appended) below the Toplevel.我想让ana2作为ana2下面的第二个字典(附加)。

OUT: {'bush_mod': {'ana1_lin_001': {}},{'ana2_lin_001': {}, 'ana2_lin_002': {}}}

It would really be helpful if someone could help me with the syntax.如果有人可以帮助我解决语法问题,那真的会很有帮助。

Thanks in advance!提前致谢!

If you want to stick to nested dictionaries I think dict.update might be an option:如果你想坚持使用嵌套字典,我认为dict.update可能是一个选择:

t = {}
t['bush_mod']={}

ana1 = {}
ana1['ana1_lin_001']={}

ana2 = {}
ana2['ana2_lin_001'] = {}
ana2['ana2_lin_002'] = {}

t['bush_mod'].update(ana1)
t['bush_mod'].update(ana2)

Such that t is:这样t是:

{'bush_mod': {'ana1_lin_001': {}, 'ana2_lin_001': {}, 'ana2_lin_002': {}}}

dict.update here adds the keys-value pairs from ana1 and ana2 to the dictionary t['bush_mod ]` dict.update在这里将ana1ana2的键值对ana2到字典t['bush_mod ]`

you need to use distinct keys for each element in the dict t... it is overriding because you used 'bush_mod' twice...您需要为 dict t 中的每个元素使用不同的键...它是覆盖的,因为您使用了 'bush_mod' 两次...

you need to make t['bush_mod']= [] then append that list with things.您需要使 t['bush_mod']= [] 然后在该列表中附加一些东西。

t['bush_mod'] = []
t['bush_mod'].append(ana1)
t['bush_mod'].append(ana2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM