How can I add new keys to a dictionary?

前端 未结 16 2641
梦毁少年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:16
    dictionary[key] = value
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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' )
    
    0 讨论(0)
  • 2020-11-22 01:23

    I think it would also be useful to point out Python's collections module that consists of many useful dictionary subclasses and wrappers that simplify the addition and modification of data types in a dictionary, specifically defaultdict:

    dict subclass that calls a factory function to supply missing values

    This is particularly useful if you are working with dictionaries that always consist of the same data types or structures, for example a dictionary of lists.

    >>> from collections import defaultdict
    >>> example = defaultdict(int)
    >>> example['key'] += 1
    >>> example['key']
    defaultdict(<class 'int'>, {'key': 1})
    

    If the key does not yet exist, defaultdict assigns the value given (in our case 10) as the initial value to the dictionary (often used inside loops). This operation therefore does two things: it adds a new key to a dictionary (as per question), and assigns the value if the key doesn't yet exist. With the standard dictionary, this would have raised an error as the += operation is trying to access a value that doesn't yet exist:

    >>> example = dict()
    >>> example['key'] += 1
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    KeyError: 'key'
    

    Without the use of defaultdict, the amount of code to add a new element would be much greater and perhaps looks something like:

    # This type of code would often be inside a loop
    if 'key' not in example:
        example['key'] = 0  # add key and initial value to dict; could also be a list
    example['key'] += 1  # this is implementing a counter
    

    defaultdict can also be used with complex data types such as list and set:

    >>> example = defaultdict(list)
    >>> example['key'].append(1)
    >>> example
    defaultdict(<class 'list'>, {'key': [1]})
    

    Adding an element automatically initialises the list.

    0 讨论(0)
  • 2020-11-22 01:24

    The conventional syntax is d[key] = value, but if your keyboard is missing the square bracket keys you could also do:

    d.__setitem__(key, value)
    

    In fact, defining __getitem__ and __setitem__ methods is how you can make your own class support the square bracket syntax. See https://python.developpez.com/cours/DiveIntoPython/php/endiveintopython/object_oriented_framework/special_class_methods.php

    0 讨论(0)
  • "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.

    0 讨论(0)
提交回复
热议问题