简体   繁体   中英

adding keys in nested dictionary in python

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

Add an is_noble_gas boolean entry to the hydrogen and helium dictionaries.

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}}

You should access the dictionary and add is_noble_gas as a new key to the dictionary as follows.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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