Built with Tutify.io

    AIStudyLabs

    Python Add keys to Dictionary

    Python Add keys to Dictionary

    Python provides several ways to add new keys to a dictionary. Dictionaries are data type in python, that allows you to store key-value pairs. To add keys to the dictionary in Python, you can use the square bracket notation, the update() method, the dict.setdefault() method, and dictionary unpacking. In this article, we'll explain these methods with examples.

    Methods to Add Keys to Dictionary

    <a id="h-1-quick-examples-to-add-new-keys-to-dictionary"></a>

    1. Quick Examples to Add New Keys to Dictionary

    Before we explore the various ways to add new keys to a dictionary in Python, let's take a quick look at some examples.

    
    # Create an empty dictionary
    my_dict = {}
    
    # Add new keys using square bracket notation
    my_dict['Python'] = 1991
    my_dict['Java'] = 1995
    
    # Add new keys using the update() method
    my_dict.update({'JavaScript': 1995, 'Ruby': 1995})
    
    # Add new keys using the setdefault() method
    my_dict.setdefault('Go', 2009)
    my_dict.setdefault('Swift', 2014)
    
    # Add new keys using the dict() constructor
    new_languages = dict(Csharp=2000, Rust=2010)
    my_dict.update(new_languages)
    
    # Add new keys using dictionary comprehension
    more_languages = {'Kotlin': 2011, 'TypeScript': 2012}
    my_dict = {**my_dict, **more_languages}
    

    <a id="h-2-using-the-notation"></a>

    2. Using the [] Notation

    One of the simplest and most commonly used approaches to add new keys to a Python dictionary is using the [] notation. The advantage of this approach is its simplicity and readability. It is a very efficient method in terms of performance, as it does not require the use of any additional functions or methods.

    
    # Create a dictionary
    my_dict = {'Python': 1991, 'Ruby': 1995, 'Go': 2009}
    
    # Add new keys using [] notation
    my_dict['Java'] = 1995
    my_dict['JavaScript'] = 1995
    
    print(my_dict)
    

    Yields the following output:

    
    # Output:
    {
        'Python': 1991, 
        'Ruby': 1995, 
        'Go': 2009, 
        'Java': 1995, 
        'JavaScript': 1995
    }
    

    It is worth noting that if the key already exists in the dictionary, it will overwrite the existing key with the new value.

    <a id="h-3-using-the-update-method"></a>

    3. Using the update() Method

    The update() method is another commonly used approach to add new keys to a Python dictionary. This method takes a dictionary as an argument and adds the key-value pairs from that dictionary to the original dictionary.

    If a key already exists in the original dictionary, its value will be updated with the value from the argument dictionary. One advantage of the update() method is that it allows for the addition of multiple key-value pairs at once.

    
    # Add new keys using update() method
    my_dict = {'Python': 1991}
    new_dict = {'Java': 1995, 'JavaScript': 1995}
    my_dict.update(new_dict)
    
    print(my_dict)
    
    # Output : 
    {'Python': 1991, 'Java': 1995, 'JavaScript': 1995}
    

    It is important to note that the update() method modifies the original dictionary in place, which may not always be desirable.

    <a id="h-4-using-the-setdefault-method"></a>

    4. Using the setdefault() Method

    The setdefault() method is a dictionary method that provides a convenient way to add new keys to a dictionary without overwriting existing keys. This method takes two arguments: the first argument is the key that you want to add, and the second argument is the default value for that key.

    
    # Add new keys using setdefault() method
    my_dict.setdefault('Java', 1995)
    my_dict.setdefault('JavaScript', 1995)
    
    print(my_dict)
    

    If the key is already in the dictionary, setdefault() will simply return the existing value.

    <a id="h-5-using-the-dict-constructor"></a>

    5. Using the dict() Constructor

    The dict() constructor in Python can also be used to add new keys to a dictionary. This method creates a new dictionary object and allows you to specify key-value pairs using keyword arguments.

    
    # Add new Keys to the dict
    my_dict = dict(my_dict, Java=1995, Cpp=1983)
    print(my_dict)
    

    If you pass in a key that already exists in the dictionary, its value will be updated. Otherwise, a new key-value pair will be added to the dictionary.

    <a id="h-6-using-dictionary-comprehension"></a>

    6. Using Dictionary Comprehension

    Dictionary comprehension is a concise and elegant way to create dictionaries in Python. It is a one-liner for-loop that iterates over a sequence of items and creates a dictionary based on the key-value pairs returned by the loop.

    Using dictionary comprehension, you can also add new key-value pairs to an existing dictionary. To do this, you simply add a conditional expression to the comprehension that specifies the new key-value pairs.

    
    new_keys = {'Java': 1995, 'Cpp': 1983}
    # Adding new Keys 
    my_dict = {**my_dict, **{key: value for key, value in new_keys.items() if key not in my_dict}}
    print(my_dict)
    

    You can create a new dictionary from an iterable object like a list, and specify the key-value pairs using a simple expression. You can then merge this new dictionary with an existing dictionary using the unpacking operator **.

    <a id="h-7-comparision-the-best-method"></a>

    7. Comparision - The Best Method

    Adding new keys to a dictionary in Python, there are several methods available, each with its own advantages and disadvantages. After running multiple tests on different methods to add new keys to a dictionary, the [] notation method was found to be the fastest.

    This is because it involves a direct reference to the dictionary and a simple assignment statement, which is a straightforward and efficient operation.

    
    import timeit
    
    my_dict = {
        'Python': 1991, 
        'Ruby': 1995, 
        'Go': 2009
    }
    
    # Using the [] notation
    t1 = timeit.timeit(stmt="my_dict['Java'] = 1995", number=1000000, globals=globals())
    
    # Using the update() method
    t2 = timeit.timeit(stmt="my_dict.update({'JavaScript': 1995})", number=1000000, globals=globals())
    
    # Using the setdefault() method
    t3 = timeit.timeit(stmt="my_dict.setdefault('PHP', 1995)", number=1000000, globals=globals())
    
    # Using the dict() constructor
    t4 = timeit.timeit(stmt="new_dict = dict(my_dict); new_dict['C++'] = 1983", number=1000000, globals=globals())
    
    # Using dictionary comprehension
    t5 = timeit.timeit(stmt="{**my_dict, 'Rust': 2010}", number=1000000, globals=globals())
    
    print("Adding a new key to a dictionary:")
    print("[] notation:         ", t1)
    print("update() method:     ", t2)
    print("setdefault() method: ", t3)
    print("dict() constructor:  ", t4)
    print("dictionary comp:      ", t5)
    

    Yields the following output on my system but it may vary on your system.

    
    Adding a new key to a dictionary:
    [] notation:          0.0964382999954978
    update() method:      0.5524427999989712
    setdefault() method:  0.13088589999824762
    dict() constructor:   0.5254891000004136
    dictionary comp:       0.6200347000049078
    

    <a id="h-8-summary-and-conclusion"></a>

    8. Summary and Conclusion

    Adding new keys to a Python dictionary is a common task in many programs. We discussed [] notation, update() method, setdefault() method, dict() constructor, and dictionary comprehension. I hope this article has provided you with a good understanding of how to add new keys to a dictionary in Python using different methods. If you have any further questions comment below.

    Happy coding!

    <a id="h-related-articles"></a>

    Related Articles