Python adding key to dict

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.

  • Using the [] Notation
  • Using the update() Method
  • Using the setdefault() Method
  • Using the dict() Constructor
  • Using Dictionary Comprehension
  • Comparision – The Best Method
  • Summary and Conclusion

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() # 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 = my_dict =

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 = # Add new keys using [] notation my_dict['Java'] = 1995 my_dict['JavaScript'] = 1995 print(my_dict) 

Yields the following output:

Читайте также:  Python узнать методы модуля

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

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 = new_dict = my_dict.update(new_dict) print(my_dict) # Output :

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

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.

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.

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 = # Adding new Keys my_dict = <**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 ** .

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()", 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 

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.

You may also like reading:

Источник

How to Add a Key To a Dictionary in Python – Definitive Guide

Stack Vidhya

Python Dictionary is used to store the data in the key-value pair.

You can add a key to dictionary in python using mydict[«newkey»] = «newValue» method.

This tutorial teaches you the different methods to add a key to a dictionary in Python

Using Subscript Notation ( [ ] Operator)

The subscript notation is defined as square brackets [] , and it’s used to access the elements of the list or set of a dictionary.

Together with [] and = operators, you can also assign a key-value pair to an existing dictionary object.

The following code shows how to add a new key to a dictionary object.

mydict = print(mydict) mydict["newlyAddedkey"] = "newlyAddedValue" print(mydict)

This is also known as appending a new key value to the dictionary.

Using Update() method

In this section, you’ll learn how to add new key-value to existing dict using the update() method.

It accepts a mandatory mapping parameter which is also another dictionary consisting of one or more key-value pairs.

The following example shows how new keys and values can be added to a dictionary using the update() method.

mydict = new_dict = mydict.update(new_dict) print(mydict)

Using __setitem()__ method

In this section, you’ll learn how to add new keys to the dictionary using the setitem() method in Python.

It is not recommended to use this method considering performance complexity.

setItem() accepts key and value as parameters and sets the value into the calling object.

The following example shows how to add a new key to a dictionary using the setitem() method.

mydict = # using __setitem__ method mydict.__setitem__("newkey2", "Vidhya") print(mydict)

Using ** operator

In this section, You’ll add a new Key-value Using ** operator.

This operator denotes dictionary unpacking. This operator’s operand must be a mapping.

Each mapping item is added to the new dictionary.

Using ** in front of key-value pairs like ** will unpack it as a new dictionary object.

The following code shows how the ** object unpacks two dictionary objects and adds them to a new dictionary object.

mydict = < "one": "1", "two": "2", "three": "3", "four": "4", ># Using ** will create a new dictionary my_new_dict = <**mydict, **<"five": "5">> print(mydict) print("\nNew Dictionary with new key value pair added:") print(my_new_dict) 
 New Dictionary with new key value pair added:

Using Merge Operator

In this section, you’ll learn how to add new keys to the Python dictionary using the Python merge operator.

This merge operator is available since python version 3.9 .

You can check the Python version in cmd using the below command.

import sys print(sys.version)
3.9.2 (default, Sep 4 2020, 00:03:40) [MSC v.1916 32 bit (Intel)]

There are two types of the merge operations.

First Method using Merge

Two dictionaries will be merged and a new dictionary will be created when you use | operator between two dictionaries.

num1 = num2 = # Merge operator numbers = num1 | num2 print("Created new Dictionary using merge : ", numbers)
Created new Dictionary using merge :

Second Method using Merge

The items from the second dictionary will be merged into the first dictionary rather than creating a new dictionary object when you use |= operator between two dictionaries.

# Update operator, keys from the second dictionary added to first. num1 |= num2 print("using update:", num1)

Add new key value pair to dictionary without overwriting

In this section, you’ll learn how to add new key-value pairs to the dictionary without overwriting the existing key-value pairs.

This can be done by checking if the key already exists in the dictionary using the in operator and the if statements.

Before adding a new key to the dictionary,

  • if «one» not in mydict is used to check if the key doesn’t exist in the dictionary.
  • If this statement is evaluated to true , then the key will be added to the dictionary.
  • If evaluated to false, an error message will be printed.
mydict = if "one" not in mydict: mydict["one"] = "11" else: print("Dictionary already has key : One. Hence value is not overwritten ") print(mydict)
 Dictionary already has key : One. Hence value is not overwritten

In the below example, the key “ four ” is not available in the dictionary. Hence it’ll be added to the dictionary.

if "four" not in mydict: mydict["four"] = "4" print("\nAdded new key value pair to dictionary without overwriting") print(mydict)
Added new key value pair to dictionary without overwriting

Add new key to dictionary without value

You can add a new key to the dictionary without value using the None keyword. It’ll just add a new key to the dictionary.

mydict = < "0": "zero", "1": "one", "2": "two" >mydict["keywithoutvalue"] = None print(mydict)

You’ll see the below output, where there is a key named keywithoutvalue exists without any value.

Additional Resources

Источник

Оцените статью