How can I add new keys to a dictionary?

前端 未结 16 3019
梦毁少年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:26

    Let's pretend you want to live in the immutable world and do NOT want to modify the original but want to create a new dict that is the result of adding a new key to the original.

    In Python 3.5+ you can do:

    params = {'a': 1, 'b': 2}
    new_params = {**params, **{'c': 3}}
    

    The Python 2 equivalent is:

    params = {'a': 1, 'b': 2}
    new_params = dict(params, **{'c': 3})
    

    After either of these:

    params is still equal to {'a': 1, 'b': 2}

    and

    new_params is equal to {'a': 1, 'b': 2, 'c': 3}

    There will be times when you don't want to modify the original (you only want the result of adding to the original). I find this a refreshing alternative to the following:

    params = {'a': 1, 'b': 2}
    new_params = params.copy()
    new_params['c'] = 3
    

    or

    params = {'a': 1, 'b': 2}
    new_params = params.copy()
    new_params.update({'c': 3})
    

    Reference: https://stackoverflow.com/a/2255892/514866

提交回复
热议问题