How can I add new keys to a dictionary?

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

    "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."

    Yes it is possible, and it does have a method that implements this, but you don't want to use it directly.

    To demonstrate how and how not to use it, let's create an empty dict with the dict literal, {}:

    my_dict = {}
    

    Best Practice 1: Subscript notation

    To update this dict with a single new key and value, you can use the subscript notation (see Mappings here) that provides for item assignment:

    my_dict['new key'] = 'new value'
    

    my_dict is now:

    {'new key': 'new value'}
    

    Best Practice 2: The update method - 2 ways

    We can also update the dict with multiple values efficiently as well using the update method. We may be unnecessarily creating an extra dict here, so we hope our dict has already been created and came from or was used for another purpose:

    my_dict.update({'key 2': 'value 2', 'key 3': 'value 3'})
    

    my_dict is now:

    {'key 2': 'value 2', 'key 3': 'value 3', 'new key': 'new value'}
    

    Another efficient way of doing this with the update method is with keyword arguments, but since they have to be legitimate python words, you can't have spaces or special symbols or start the name with a number, but many consider this a more readable way to create keys for a dict, and here we certainly avoid creating an extra unnecessary dict:

    my_dict.update(foo='bar', foo2='baz')
    

    and my_dict is now:

    {'key 2': 'value 2', 'key 3': 'value 3', 'new key': 'new value', 
     'foo': 'bar', 'foo2': 'baz'}
    

    So now we have covered three Pythonic ways of updating a dict.


    Magic method, __setitem__, and why it should be avoided

    There's another way of updating a dict that you shouldn't use, which uses the __setitem__ method. Here's an example of how one might use the __setitem__ method to add a key-value pair to a dict, and a demonstration of the poor performance of using it:

    >>> d = {}
    >>> d.__setitem__('foo', 'bar')
    >>> d
    {'foo': 'bar'}
    
    
    >>> def f():
    ...     d = {}
    ...     for i in xrange(100):
    ...         d['foo'] = i
    ... 
    >>> def g():
    ...     d = {}
    ...     for i in xrange(100):
    ...         d.__setitem__('foo', i)
    ... 
    >>> import timeit
    >>> number = 100
    >>> min(timeit.repeat(f, number=number))
    0.0020880699157714844
    >>> min(timeit.repeat(g, number=number))
    0.005071878433227539
    

    So we see that using the subscript notation is actually much faster than using __setitem__. Doing the Pythonic thing, that is, using the language in the way it was intended to be used, usually is both more readable and computationally efficient.

提交回复
热议问题