adding keys in nested dictionary in python

前端 未结 3 1505
温柔的废话
温柔的废话 2021-01-23 02:04
elements = {\'hydrogen\': {\'number\': 1, \'weight\': 1.00794, \'symbol\': \'H\'}, 
            \'helium\': {\'number\': 2, \'weight\': 4.002602, \'symbol\': \'He\'}}


        
相关标签:
3条回答
  • 2021-01-23 02:19
    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}}

    0 讨论(0)
  • 2021-01-23 02:30
    elements['hydrogen']['is_noble_gas'] = False
    elements['hydrogen']['is_noble_gas'] = True
    
    0 讨论(0)
  • 2021-01-23 02:41

    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
    
    0 讨论(0)
提交回复
热议问题