Add to Dictionary Python

Learn via video course
FREE
View all courses
Python Course for Beginners With Certification: Mastering the Essentials
Python Course for Beginners With Certification: Mastering the Essentials
by Rahul Janghu
1000
4.90
Start Learning
Python Course for Beginners With Certification: Mastering the Essentials
Python Course for Beginners With Certification: Mastering the Essentials
by Rahul Janghu
1000
4.90
Start Learning
Topics Covered

Overview

In this article, we'll look at how to Add to Dictionary in Python. We will append new keys to a dictionary using seven different methods.

A dictionary is a collection of key-value pairs, with the value being any Python object. On the other hand, the keys are immutable Python objects such as numbers, strings, or tuples. We will look at the different ways in which we can add a new key: dictionary value pair.

What is a Dictionary in Python?

add-to-dictionary-in-python

A Dictionary in Python is one of the most popular data structures. They are used to store data in a key-value pair format. The values of the Python dictionary may or may not be unique, but the keys tend to be unique. The values within a dictionary can be of any data type, but the thing to note is that the keys are immutable. Hence, the key can only be strings, numbers, or tuples.

How to Add to Dictionary in Python?

The idea of adding a pair of elements to a dictionary is quite simple and easy. As dictionaries cannot have two items with the same key, when a key is already there, its value is altered. And if the key is not present, a new fresh set of key-value pairs is created by the system.

Adding to new elements can be done using the assignment operator "=".

Different Methods to Add to Dictionary in Python

Let's look into different ways of adding a key: value pair to the dictionary.

Method - 1: Add to Dictionary Using the Subscript Notation

The subscript method will create a new key-value pair on a dictionary by assigning a value to that key. As mentioned and discussed above, if the key doesn’t exist, it will be added and will point to the given value. If the key already exists, the current value will be overwritten to the previous value.

Let's see an example to see this works:

add-to-dictionary-in-python-1

Output:

We can see that the keys like key1 and key2 already exist in the dict dictionary. That's why when we added a new pair on line 6, the value of that key is modified or overwritten as the dict is mutable. whereas on line 7, the key "key3" was not present, so a new set of key: value pairs were added to the original dictionary.

Method - 2: Add to Dictionary Using the Update Method

The update() method is useful when we need to update or add several key/value pairs to the dictionary. The dictionary's given elements are added using the update() method.

add-to-dictionary-in-python-2

Output:

We started with a dict dictionary where we already initiated two pairs of keys and values. Later on line 5, we added a new key-value pair using the update method, which takes the whole object and appends it to the end of the dictionary.

On line 9, we created a new dictionary dict1 where we set keys like 4 and 5, which were not present in the dict dictionary. Using line 10, we appended the whole dictionary to the dict dictionary using the update method and printed it.

On line 14, we used the update method to add elements or key: value pairs using the assignment operator by not forming an independent dictionary, which we were doing before.

Method - 3: Using the "setitem" Method

Using the setitem method, you can add a key-value pair to a dict. Due to its poor performance, it should be avoided (computationally inefficient).

However, let's see an example of how to work with the setitem method.

Output:

Line 4, We used the setitem method to add a new key: value pair to the dict.

Method - 4: Add to Dictionary in Python Using the "**" Operator

We can combine the new key-value pair with the old dictionary to create a new dictionary. When a key-value pair is preceded by the symbol **, such as **'c': 3, a new dictionary object is created.

Output:

We created a new_dict dictionary on line 3, which append the previous dict dictionary and a new set of key: value pair using the ** Operator.

Method - 5: Using the “in” Operator and IF Statements

If the key is present, the above methods will automatically overwrite any existing value. If you are aware that your program may contain duplicate keys, it is best to use a conditional append rather than directly appending the values.

To ensure that the keys in the dictionary are not overwritten, you can use an if condition here.

Here's a simple example of how you can do it. You can also use the try-catch exception, but using an if condition is the simplest to start with.

Output:

Instead of simply assigning, we conditionally append the values after determining whether or not the keys are present. Because the key 'a' already exists, the if statement in line 2 returns false, preventing the assignment in line 3 from being performed. Lines 5 and 8 do not have the respective keys, so the assignment is performed without overwriting the existing value.

Method - 6: Adding by Using enumerate() Method and a for Loop

Make a list of the components. Iterate through the list using the enumerate() method, and then add each item to the dictionary by using its index as a key for each value.

The Python enumerate() method accepts any iterable as input and produces an enumerate object that may be used to explore the iterable. It holds the index and the associated item in an iterable object such as a list, tuple, or string.

Using dictionary comprehension, an enumerated object containing an index and a value is turned into a dictionary.

Let's see how that work with an example.

Output:

On line 3, we used a dictionary comprehension which iterates over an enum object and forms a dictionary which key and value pair.

Method - 7: Add to Dictionary Python Using Zip

The zip(fields, values) method generates two-item tuples and returns an iterator. You can create the dictionary you need by calling dict() on that iterator. The first list's items become the dictionary's keys, and the second list's elements represent the dictionary's values.

In this example, we are using Python's zip method to add keys and values to an empty dictionary. You can also use an in the existing dictionary instead of a dictionary = to add elements to the dictionary.

Output:

There is another option to use dict() with zip(), which would loop by itself so we don't have to externally.

Output:

In this example, we have defined two lists that we need to convert into a dictionary. The first list of items will be keys for the dictionary, and the second list of items will be the dictionary.

Learn More

To learn more about dictionary in Python and how it works visit this Article.

Conclusion

  • A dictionary is a collection of key-value pairs with the value being any Python object.
  • The idea of adding a pair of elements to the dictionary is quite simple and easy. As dictionaries cannot have two items with the same key, when a key is already there, its value is altered. And if the key is not present, a new fresh set of key: value pairs are created by the system.
  • The subscript method will create a new key-value pair on a dictionary by assigning a value to that key.
  • The update() method is useful when we need to update or add several key-value pairs to the dictionary. The dictionary’s given elements are added using the update() method.
  • Using the setitem method, you can add a key-value pair to a dict. Due to its poor performance, it should be avoided (computationally inefficient).
  • We can combine the new key-value pair with the old dictionary to create a new dictionary. When a key-value pair is preceded by the symbol "**".
  • To ensure that the keys in the dictionary are not overwritten, you can use conditional appending.
  • Using dictionary comprehension, an enumerated object containing an index and a value is turned into a dictionary.
  • The zip(fields, values) method generates two-item tuples and returns an iterator. You can create the dictionary you need by calling dict() on that iterator.