在python中添加嵌套字典中的键

时间:2017-11-13 09:35:21

标签: python dictionary nested

elements = {'hydrogen': {'number': 1, 'weight': 1.00794, 'symbol': 'H'}, 
            'helium': {'number': 2, 'weight': 4.002602, 'symbol': 'He'}}

在氢和氦字典中添加is_noble_gas布尔条目。

3 个答案:

答案 0 :(得分:2)

elements = {'hydrogen': {'number': 1, 'weight': 1.00794, 'symbol': 'H'}, 'helium': {'number': 2, 'weight': 4.002602, 'symbol': 'He'}}
noble_dict = { "hydrogen": False, "helium": True }
for noble in noble_dict:
    elements[ noble ][ "is_noble_gas" ] = noble_dict[ noble ]
  

{'氦':{'符号':'他','数字':2,'重量':4.002602,'is_noble_gas':真},'氢':{'符号':'H','数字':1,'重量':1.00794,'is_noble_gas':False}}

答案 1 :(得分:2)

您应该访问字典并将is_noble_gas添加为字典的新密钥,如下所示。

>>> elements['hydrogen']['is_noble_gas'] = False
>>> elements['helium']['is_noble_gas'] = True

答案 2 :(得分:0)

elements['hydrogen']['is_noble_gas'] = False
elements['hydrogen']['is_noble_gas'] = True