How can I add new keys to a dictionary?

前端 未结 16 3170
梦毁少年i
梦毁少年i 2020-11-22 00:40

Is it possible to add a key to a Python dictionary after it has been created?

It doesn\'t seem to have an .add() method.

16条回答
  •  感动是毒
    2020-11-22 01:23

    This popular question addresses functional methods of merging dictionaries a and b.

    Here are some of the more straightforward methods (tested in Python 3)...

    c = dict( a, **b ) ## see also https://stackoverflow.com/q/2255878
    c = dict( list(a.items()) + list(b.items()) )
    c = dict( i for d in [a,b] for i in d.items() )
    

    Note: The first method above only works if the keys in b are strings.

    To add or modify a single element, the b dictionary would contain only that one element...

    c = dict( a, **{'d':'dog'} ) ## returns a dictionary based on 'a'
    

    This is equivalent to...

    def functional_dict_add( dictionary, key, value ):
       temp = dictionary.copy()
       temp[key] = value
       return temp
    
    c = functional_dict_add( a, 'd', 'dog' )
    

提交回复
热议问题