Python Program to Add Elements to a Dictionary


High-level, all-purpose Python is a very well-liked programming language. Python is utilised for cutting-edge software development projects like web development and machine learning applications.

In this article, we will be learning various methods for adding elements to a dictionary.

What do You Understand From Dictionary in Python?

A dictionary in Python stores a key: value pair, unlike other Data Types that only contain a single value as an element. It is used to store data values like a map. The dictionary includes key-value pairs to help it become more efficient.

In a dictionary, each key-value pair is separated by a colon; in contrast, each key is separated by a comma. The key values of a dictionary can be repeated and can be of any type, but the key values must be distinct and of immutable data types like Strings, Integers, and tuples.

Syntax

Key:value

First let’s learn how to create a dictionary −

We can create the dictionary in various ways like the functional where you first create the dictionary class then define the _init_ function. As we know the dictionary holds the keyvalue pairs next we will write the function to add the key:value and at the end the main function.

But here we will create a simple dictionary.

Example

Following example shows how to create a dictionary in python.

# Let's create a dictionary here
create_dictionary = {'Name': 'Devang', 'Age': 24, 'Quality': 'Hardworking'}
print(create_dictionary)

Output

{'Name': 'Devang', 'Age': 24, 'Quality': 'Hardworking'}

Till now we have cleared our basics. Now let’s apply those basics in adding the elements in the dictionary. There are various methods of doing the same but here we will understand the four simplest and important methods.

Using the update() Method

This method here is used for updating the dictionary from an iterable key:value pairs or from the elements of different dictionary object. This method is suitable because it makes the task easy when we have to add many key/ value pairs.

Syntax

dict.update([other])

Example

In the following program, a dictionary called dict is created with two key-value pairs. Then the program prints out the initial version of the dictionary. The next line adds another keyvalue pair to the dictionary and updates it. After that, a new dictionary called 'dictionary_A' is created containing two more key-value pairs which are then added to dict using .update() method and printed out in final step.

dict = {'1': 'An', '2': 'Apple a day'}
print( "First Dictionary is as following :", dict)

# for adding the key3 that is an another key
dict.update({'3': 'keeps doctor'})
print( "Updated version of Dictionary is as following : ", dict)

# for adding from dictionary_A (key4 and key5) to dict
dictionary_A = {'4': 'is', '5': 'away'}
dict.update(dictionary_A)
print(dict)

Output

First Dictionary is as following : {'1': 'An', '2': 'Apple a day'}
Updated version of Dictionary is as following : {'1': 'An', '2': 'Apple a day', '3': 'keeps doctor'}
{'1': 'An', '2': 'Apple a day', '3': 'keeps doctor', '4': 'is', '5': 'away'}

Using a For Loop and enumerate() Methods

Python provides a built-in function that is the enumerate() method. It works as adding the counter to an iterable and returns in the form of the enumerating object.

Algorithm

First make a list of elements then use the enumerate() method for iterating the list. Next, add each element to the dictionary by using the index as a key for each value taken.

Example

The program has, a dictionary and list which are created. Then, the for loop iterates through each item in the secondlist and assigns it to a key in firstlist with its corresponding index as the key value. The print statement prints out the final version of firstlist after being modified by the for loop.

firstlist = {"Apple": 1, "Boy": 2, "Cat": 3}
secondlist = ["first: 1", "second:2", "third:3"]
for i, val in enumerate(secondlist):
   firstlist[i] = val
print(firstlist)

Output

{'Apple': 1, 'Boy': 2, 'Cat': 3, 0 : 'first : 1', 1 : 'second : 2', 2 : 'third : 3'}

Using the Zip Method

When using containers or iterables, the zip() function in Python creates a single iterator object that contains the mapped values from each container. It is used to map the shared index of several containers so that a single entity can access all of them. An existing dictionary can be used in place of dictionary{}.

Example

The following program is creating a dictionary with three keys (1, 2, 3) and values ("Ship", "for", "sale"), then it prints the resulting dictionary.

dictionary = {}
keys_num = ['1', '2', '3']
values_first = ['Ship', 'for', 'sale']
for keys_num, value_first in zip(keys_num, values_first):
   dictionary[keys_num] = value_first
print(dictionary)

Output

{‘1’: ‘Ship’, ‘2’: ‘for’, ‘3’: ‘sale’}

By Using the “in” Operator and If Statements

In this method we have used the, if statement which checks if the key is already present in the dictionary. It adds the key to the dictionary if it is absent and if evaluated and finds the key is already present it presents the output as key is already present in the dictionary.

Example

The following program is creating a dictionary called "firstdictionary" with the keys "apple", "boy", and "cat". It then checks if the key "dog" exists in firstdictionary. If it does not, it adds the key-value pair ("dog": 4) to the dictionary. Otherwise, it prints out a message saying that the key is already present in the dictionary and its value will not be overwritten. Finally, it prints out all of firstdictionary's contents.

firstdictionary = {"apple": 1, "boy": 2, "cat": 3}
if "dog" not in firstdictionary:
   firstdictionary["dog"] = "4"
else:
   print("Key is already present in the dictionary : One. Hence value is not overwritten ")
print(firstdictionary)

Output

{'apple': 1, 'boy': 2, 'cat': 3, 'dog': '4'}

Example

Here, we have created a difference using the example, where if the key is absent case1 is presented otherwise case2.

firstdictionary = {"apple": 1, "boy": 2, "cat": 3, "dog": 4}
if "dog" not in firstdictionary:
   firstdictionary["dog"] = "4"
else:
   print("Key is already present in the dictionary : One. Hence value is not overwritten ")
print(firstdictionary)

Output

Key is already present in the dictionary : One. Hence value is not overwritten {'apple': 1, 'boy': 2, 'cat': 3, 'dog': 4}

Using the ** Operator

In this method, we can directly merge two dictionaries together that is the old and the key/value pair of the new dictionary using the ** operator. Hence, the work of ** operator is to unpack the key/value pair into the new dictionary object.

Algorithm

Make a dictionary, then another dictionary which we want to merge in the original dictionary. Then apply the **operator in front of the key/value pairs.

Example

There’s one more method _setitem_ method to add the elements to the dictionary but it is computationally inefficient method so we generally do not apply this method.

firstdictionary = {'apple': 1, 'boy': 2}
new_dictionary = {**firstdictionary, **{'cat': 3}}
print(firstdictionary)
print(new_dictionary)

Output

{'apple': 1, 'boy': 2}
{'apple': 1, 'boy': 2, 'cat': 3}

Conclusion

In this article we have explained five different methods which show five different approaches to do the same task which is to add elements to the dictionary using python.

Updated on: 24-Apr-2023

90 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements