在python的嵌套字典中添加键

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

将is_noble_gas布尔条目添加到氢和氦字典中.

解决方法:

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 ]

{‘helium’: {‘symbol’: ‘He’, ‘number’: 2, ‘weight’: 4.002602, ‘is_noble_gas’: True}, ‘hydrogen’: {‘symbol’: ‘H’, ‘number’: 1, ‘weight’: 1.00794, ‘is_noble_gas’: False}}

上一篇:Python sorted()函数不应该按照它应该的方式工作


下一篇:PHP使每个循环的数组更深入一级