Python Add To The Dictionary – A Guide

Python is a widely used computer programming language for creating websites and software, automating tasks, and performing data analysis. Python is a general-reason language. It may be used to create lots of distinct applications and isn’t precise to a selected problem. This versatility and simplicity of use for novices make it one of the maxima broadly used programming languages today. Python Dictionary has come to be one of the maximum famous programming languages withinside the globe in current years. It’s used for the whole thing from gadget mastering to developing websites and software program testing. It may be utilized by each builder and non-builders.

Python Add To The Dictionary - A Guide

There are one-of-a-kind forms of information sorts in Python. One of them is a dictionary.

Dictionary:

Dictionaries are one of the vital statistics kinds to be had in Python. Dictionary statistics are saved as key/cost pairs. They are separated via way of means of a colon (:) and the key/cost pairs are separated via way of means of a comma (,).

Dictionary keys are unique and can be strings, integers, tuples, and so on. The value can be a list or a list in a list, a number, a string, and so on.

  • In the latest Python version, the dictionaries are ordered (that is, the order of the elements is fixed and cannot be changed), but in older versions, the dictionaries are not ordered, so the order is uncertain). 
  • The dictionary can be changed. You can also add elements, change their values, and remove them. 
  • The dictionary does not allow duplicate keys (that is, the same key for different values).

The following is an example of how to create a dictionary in python:

#code to create a dictionary in python

MY_dICTIONARY={“Priyanshu”:“Java”,“Pavan”:“Python”,“Ganesh”:“Javascript”}

#printing the created dictionary..

print(MY_dICTIONARY)

Output :

{‘Priyanshu’: ‘Java’, ‘Pavan’: ‘Python’, ‘Ganesh’: ‘Javascript’}

Dictionaries do not allow duplicate keys. Let us see about it :

#code to write the dictionary with a duplicate key.

#Creating a dictionary.

MY_dICTIONARY={“Priyanshu”:“Java”,“Pavan”:“Python”,“Ganesh”:“Javascript”,“Priyanshu”:“C/C++” }

#printing the dictionary..

print(MY_dICTIONARY)

Output :

{‘Priyanshu’: ‘C/C++’, ‘Pavan’: ‘Python’, ‘Ganesh’: ‘Javascript’}

Dictionaries can contain values of any datatypes :

#code  showing that dictionaries can contain values of any data type

record = {

  “Name”: “Priyanshu”,

  “doctor”: False,

  “Age”: 20,

  “languages”: [“Hindi”, “English”, “Rajasthani”,      “Telugu”]

}

#printing the dictionary.

print(record)

Output :

{‘Name’: ‘Priyanshu’, ‘doctor’: False, ‘Age’: 20, ‘languages’: [‘Hindi’, ‘English’, ‘Rajasthani’, ‘Telugu’]}

Let us see how to access the elements in  a given dictionary:  

 Dictionary data is available in key/value pairs. To access the elements of the dictionary, you need to use the square brackets ([`key`]) that contain the keys. 

 This is an example showing how to access an item in a dictionary using the keys in square brackets.

#code to access the elements of a given dictionary

#Creating a dictionary.

MY_dICTIONARY={“Priyanshu”:“Java”,“Pavan”:“Python”,“Ganesh”:“Javascript”,“Sai”:“C/C++”}

#printing the elements of the dictionary individually..

print(“Priyanshu:”,MY_dICTIONARY[“Priyanshu”])

print(“Pavan:”,MY_dICTIONARY[“Pavan”])

print(“Ganesh:”,MY_dICTIONARY[“Ganesh”])

print(“Sai:”,MY_dICTIONARY[“Sai”])

Output:

Priyanshu: Java

Pavan: Python

Ganesh: Javascript

Sai: C/C++

If u try to print the element which is not present in the given dictionary, then it will give you an error in the output console.

#Creating a dictionary.

MY_dICTIONARY={“Priyanshu”:“Java”,“Pavan”:“Python”,“Ganesh”:“Javascript”,“Sai”:“C/C++”}

print(“Priyanshu:”,MY_dICTIONARY[“Priyanshu”])

print(“Pavan:”,MY_dICTIONARY[“Pavan”])

print(“Ganesh:”,MY_dICTIONARY[“Ganesh”])

print(“Sai:”,MY_dICTIONARY[“Sai”])

print(“Kiran:”,MY_dICTIONARY[“Kiran”])

Output:

Traceback (most recent call last):

  File “display.py”, line 28, in <module>

    print(“Kiran:”,MY_dICTIONARY[“Kiran”])

KeyError: ‘Kiran’

Priyanshu: Java

Pavan: Python

Ganesh: Javascript

Sai: C/C++

Let us see how to count the number of elements present in a given dictionary :

#code to print the length of the dictionary

#Creating a dictionary.

MY_dICTIONARY={“Priyanshu”:“Java”,“Pavan”:“Python”,“Ganesh”:“Javascript”}

#code to print the length of the dictionary.

print(len(MY_dICTIONARY))

Output :

3

Now let us different ways to add or update elements in a given dictionary by using  different methods :

  • The keys to the dictionary are name, place, company, and age. You can use the append () method to update the value of a key in the dictionary.

#Code to append elements using the append() method.

MY_DICTIONARY = {“Name”:[], “Place”:[], “Company”:[], “Age”:[]}

#Appending elements separately to the keys in dictionary.

MY_DICTIONARY[“Name”].append(“Anshu”)

MY_DICTIONARY[“Place”].append(“New Delhi”)

MY_DICTIONARY[“Company”].append(“Google”)

MY_DICTIONARY[“Age”].append(30)

#Printing the updated dictionary

print(MY_DICTIONARY)

Output:

{‘Name’: [‘Anshu’], ‘Place’: [‘New Delhi’], ‘Company’: [‘Google’], ‘Age’: [30]}

We can see that the lists are appended with values in the dictionary in the output.

  • Let us see how to add a new key to a dictionary using the assignment operator “is equal to (‘=’)”. This is almost the same as assigning a new value to the dictionary. The Python dictionary is modifiable, so if you use the assignment operator, you just need to add a new key to your data structure. If the key already exists in the dictionary, the assignment operator automatically updates the value.

#code to add a new value using assignment operator (“=”)

#Creating a dictionary.

MY_dICTIONARY={“Priyanshu”:“Java”,“Pavan”:“Python”,“Ganesh”:“Javascript”,“Sai”:“C/C++”}

#printing old dictionary

print(“Old dictionary :”,MY_dICTIONARY)

MY_dICTIONARY[“Kiran”]=“HTML”

#Printing the  updated dictionary

print(“Current dictionary :”,MY_dICTIONARY)

Output :

Old dictionary : {‘Priyanshu’: ‘Java’, ‘Pavan’: ‘Python’, ‘Ganesh’: ‘Javascript’, ‘Sai’: ‘C/C++’}

Current dictionary : {‘Priyanshu’: ‘Java’, ‘Pavan’: ‘Python’, ‘Ganesh’: ‘Javascript’, ‘Sai’: ‘C/C++’, ‘Kiran’: ‘HTML’}

We can see that a new key “Kiran” with the value “HTML” is added to the dictionary in the output.

  • Python dictionary provides an update () method that allows you to add one dictionary to another. The update () method automatically overwrites the value of the existing key with the new key. Therefore, be cautious now no longer to by chance overwrite precious records here. To replace a current object withinside the dictionary, you want a connection with the important thing to replace the value

 Therefore, there is a dictionary my_dictionary = {“Name of the person “: “ABC”, “email”: “[email protected]”, “City “: “Mumbai”}. 

 Update City from Mumbai to New Delhi. This is an example showing how to update.

#code to update the existing value for a given key.

#code to create a new dictionary.

my_dictionary = {“Name of the person “: “ABC”, “email”: [email protected], “City “: “Mumbai”}

#Printing the old dictionary

print(“Old dictionary:”,my_dictionary)

#updating value for City from Mumbai to New Delhi

my_dictionary.update({“City “:“New Delhi”})

#Printing the updated dictionary

print(“Updated dictionary :”,my_dictionary)

Output :

Old dictionary : {‘Name of the person ‘: ‘ABC’, ’email’: ‘[email protected]’, ‘City ‘: ‘Mumbai’}

 Updated dictionary : {‘Name of the person ‘: ‘ABC’, ’email’:    ‘[email protected]’, ‘City ‘: ‘New Delhi’}

We can see that the value of key “City” is updated to “New Delhi” from “Mumbai”.

  • We can add key / value pairs to the dictionary  using the _setitem_ () method. 

 Let’s look at an example of adding a new item to the dictionary  using the _setitem_ () method.

#code to add a new item using __setitem__() method

#Creating a  dictionary 

my_dictionary = {“Name of the person “: “ABC”, “email”: [email protected], “City “: “Mumbai”}

#Printing the old dictionary

print(“Old dictionary :”,my_dictionary)

#Adding new item using __setitem__() method.

my_dictionary.__setitem__(“Age”,20)

#Printing new dictionary

print(“New dictionary :”,my_dictionary)

Output :

Old dictionary : {‘Name of the person ‘: ‘ABC’, ’email’: ‘[email protected]’, ‘City ‘: ‘Mumbai’}

New dictionary : {‘Name of the person ‘: ‘ABC’, ’email’: ‘[email protected]’, ‘City ‘: ‘Mumbai’, ‘Age’: 20}

We can see that the new item “Age ” with value 20 is added to the dictionary in the output.

  • You can use the “**” operator to add key/value pairs to the dictionary. 

 The “**” operator basically adds a key-value pair to the new dictionary and merges it with the old dictionary. 

 Let’s look at an example of adding a new item to a dictionary using the “**” operator.

#Code to add a key value pair to a dictionary using “**” operator

#Creating a dictionary

my_dictionary = {“Name of the person “: “ABC”, “email”: [email protected], “City “: “Mumbai”}

#Printing a new dictionary.

print(“Old dictionary :”,my_dictionary)

#Using ‘**’ operator.

my_dictionary={**my_dictionary,**{“Age”:20}}

#Printing the new dictionary

print(“New dictionary :”,my_dictionary)

Output :

Old dictionary : {‘Name of the person ‘: ‘ABC’, ’email’: ‘[email protected]’, ‘City ‘: ‘Mumbai’}

New dictionary : {‘Name of the person ‘: ‘ABC’, ’email’: ‘[email protected]’, ‘City ‘: ‘Mumbai’, ‘Age’: 20}

We can see that the new item “Age ” with value 20 is added to the dictionary in the output.

  • You can add the list to the dictionary using the “+” operator. 

 The “+” operator is basically used to append in the dictionary. 

 Let’s look at an example of adding a new item to a dictionary using the “+” operator.

#code to append list  to a dictionary by using ‘+’ operator.

#Creating a dictionary

my_dictionary = {‘Anshu’: [], ‘Anshul’: []}

#printing the old dictionary.

print(“Old dictionary :”,my_dictionary)

#Appending the lists using “+” operator.

my_dictionary[‘Anshu’] += [34, 35]

my_dictionary[‘Anshul’] += [45, 46]

#printing the new dictionary.

print(“New dictionary :”,my_dictionary)

Output :

Old dictionary : {‘Anshu’: [], ‘Anshul’: []}

New dictionary : {‘Anshu’: [34, 35], ‘Anshul’: [45, 46]}

We can see that values are appended to the list in the output.

  • Some of the methods automatically overwrite the existing value if the key is present. If you know that your program may have duplicate keys, it is recommended that you add conditional additions instead of adding the values ​​directly. 

 We can also use an if condition here to prevent the keys in the dictionary from being overwritten. 

 Let’s look at a simple example of how this works. However, you can also use the try-catch exception. The easiest way is to use an if condition.

#code to add elements without  overwriting .

#creating the dictionary.

my_dictionary = {“Name of the person “: “ABC”, “email”: [email protected], “City “: “Mumbai”}

#Printing the old dictionary

print(“Old dictionary :”,my_dictionary)

#Using if condition

if ‘Age’ not in my_dictionary.keys():

   my_dictionary[‘Age’] = 30

if ’email’ not in my_dictionary.keys():

   my_dictionary[’email’] = [email protected]

#printing the new dictionary.

print(“New dictionary :”,my_dictionary)

Output :

Old dictionary : {‘Name of the person ‘: ‘ABC’, ’email’: ‘[email protected]’, ‘City ‘: ‘Mumbai’}

New dictionary : {‘Name of the person ‘: ‘ABC’, ’email’: ‘[email protected]’, ‘City ‘: ‘Mumbai’, ‘Age’: 30}

Here we can observe that as ‘Age’ is not present it added that item but ’email’ is already present. So it did not overwrite it.

  • What if we want to add multiple items to a given dictionary?

We can add multiple key-value pairs to a given dictionary using update()

Let’s look at a simple example showing how to add multiple key-value pairs.

#code to add elements multiple key-value pairs to a dictionary .

#creating the dictionary.

my_dictionary = {“Name of the person “: “ABC”, “email”: [email protected], “City “: “Mumbai”}

#printing the old dictionary.

print(“Old dictionary :”,my_dictionary)

#Updating the dictionary.

my_dictionary.update([(“Age”,20),(“Company”,“Google”)])

#Printing the new dictionary

print(“New dictionary :”,my_dictionary)

Output :

Old dictionary : {‘Name of the person ‘: ‘ABC’, ’email’: ‘[email protected]’, ‘City ‘: ‘Mumbai’}

New dictionary : {‘Name of the person ‘: ‘ABC’, ’email’: ‘[email protected]’, ‘City ‘: ‘Mumbai’, ‘Age’: 20, ‘Company’: ‘Google’}

We can see in the output that multiple items are added to the given dictionary.

  • We can add lists to a dictionary by using the assignment operator.

Let’s look at an example showing how to add lists to dictionary.

#code to add lists to a dictionary .

#creating the dictionary.

my_dictionary = {“Name of the person “: “ABC”, “email”: [email protected], “City “: “Mumbai”}

#printing the old dictionary.

print(“Old dictionary :”,my_dictionary)

#Adding the list.

my_dictionary[“Marks”]=[34,35,36]

#Printing the new dictionary

print(“New dictionary :”,my_dictionary)

Output :

Old dictionary : {‘Name of the person ‘: ‘ABC’, ’email’: ‘[email protected]’, ‘City ‘: ‘Mumbai’}

New dictionary : {‘Name of the person ‘: ‘ABC’, ’email’: ‘[email protected]’, ‘City ‘: ‘Mumbai’, ‘Marks’: [34, 35, 36]}

We can see that the key “Marks” has been added to the dictionary with value as a list.

  • We can even add a dictionary to a dictionary

Let’s us look at a example showing how to add a dictionary to a dictionary.

#code to add  a dictionary to a dictionary .

#creating the dictionary.

my_record = {‘Info’: {‘Name’: ‘Anshu’, ‘Age’: 21}}

#creating another new  dictionary.

additional = {‘Additional’: {‘Number’: 1111111111, ‘Address’: ‘New delhi’}}

my_record.update(additional)

#printing the updated dictionary

print(my_record)

Output :

{‘Info’: {‘Name’: ‘Anshu’, ‘Age’: 21}, ‘Additional’: {‘Number’: 1111111111, ‘Address’: ‘New delhi’}}

We can see that the “additional” dictionary has been added to the “my_record” dictionary.

Python Add To The Dictionary – A Guide

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top