How can I add new keys to a dictionary?

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

    To add multiple keys simultaneously, use dict.update():

    >>> x = {1:2}
    >>> print(x)
    {1: 2}
    
    >>> d = {3:4, 5:6, 7:8}
    >>> x.update(d)
    >>> print(x)
    {1: 2, 3: 4, 5: 6, 7: 8}
    

    For adding a single key, the accepted answer has less computational overhead.

提交回复
热议问题