How can I add new keys to a dictionary?

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

    Here's another way that I didn't see here:

    >>> foo = dict(a=1,b=2)
    >>> foo
    {'a': 1, 'b': 2}
    >>> goo = dict(c=3,**foo)
    >>> goo
    {'c': 3, 'a': 1, 'b': 2}
    

    You can use the dictionary constructor and implicit expansion to reconstruct a dictionary. Moreover, interestingly, this method can be used to control the positional order during dictionary construction (post Python 3.6). In fact, insertion order is guaranteed for Python 3.7 and above!

    >>> foo = dict(a=1,b=2,c=3,d=4)
    >>> new_dict = {k: v for k, v in list(foo.items())[:2]}
    >>> new_dict
    {'a': 1, 'b': 2}
    >>> new_dict.update(newvalue=99)
    >>> new_dict
    {'a': 1, 'b': 2, 'newvalue': 99}
    >>> new_dict.update({k: v for k, v in list(foo.items())[2:]})
    >>> new_dict
    {'a': 1, 'b': 2, 'newvalue': 99, 'c': 3, 'd': 4}
    >>> 
    

    The above is using dictionary comprehension.

提交回复
热议问题