Dictionary operations in python with examples - Python

Dictionary operations in python with examples

Hello Guys, If you searching about dictionary operations in python than you are right place here you will learn complete Python Dictionary operations with examples so read the full blog also i provide the video class link in the middle of the blog. Python dictionary support the following operation-

1) Adding elements to Dictionary

We can add elements to an existing dictionary using assignment method. The key being added must not exist in dictionary. The following syntax is used to add element~

Syntax

<dictionary name>[<key>]=<value>

cricket (1: “Dhoni”, 2:”Virat”}

Example

cricket[3]=”Sachin”

print(cricket)

The example will first create a dictionary by the name ‘cricket’ with two element assigned to it. Next, it will add a new element to the dictionary. The key of the newly added element will be 3 and value will be “Sachin”. Finally it will print the whole dictionary which will appear on screen as {1:”Dhoni”, 2: “Virat”, 3: “Sachin”

2) Creating Dictionary using keys and values separately 

This is another method of creating a new dictionary. In this method, the keys and values are enclosed separately in parentheses and are given as argument to the zip() function of Python, The zip() function is then given as argument of dict().

<dictionary name>= dict(zip((<list of keys>), (<list of values>)))

cricket=dict(zip((1,2,3), (“Sachin”, “Lara”, “Ponting”)))

print(cricket)

The above example will create a new dictionary by the name ‘cricket’. The zip() function creates ‘key:value” pair by taking data from the two given tuples on one-to-one basis. Finally it will print the whole dictionary as follows{1: “Sachin”, 2: “Lara”, 3: “Ponting”}

3) Creating Dictionary using key: value pair as List

This is yet another method of creating a new dictionary. In this method, a List of two element Lists is passed as argument to the dict() function. Each inner List represents one key: value pair,

<dictionary name>= dict([[<key value pair>], [<key value pair>],……])

cricket=dict([[1, “Sachin”], [2, “Lara”], [3, “Pointing”]])

print(cricket)  

This example is first creating a new dictionary using a Python’s List of Lists. The inner lists are representing key:value pair for dictionary and outer list is as argument to dict() function. At the end it is printing the newly created Dictionary.

Write a program to create a dictionary with the cricketer’s name as value and index number as key. Number of element must be user dependent. Also print the elements.

c=1

ch=”y”

cricket={}

while ch==”y”:

nm=input(“Enter Cricketer’s Name:”)

cricket[c]=nm

c=c+1

ch=input(“Any more data(y/n):”)

for c in cricket:

                print(c,cricket[c])

4) Updating Dictionary element

Updating an element is similar to adding new element in the Dictionary except that in updating the key used must exist in the dictionary otherwise a new element will be added to the dictionary. The general format of updating dictionary element is;

Syntax

Example

<dictionary name>[<key>] = <value>

cricket[4]=”Hardik”

5) Deleting Dictionary element

There are two ways to delete an element from Dictionary. One using del statement and the other using pop() method.

Syntax-1

del <dictionary name>[<key>]

del cricket[2]

Example

This example will delete that entry from the dictionary whose key is 2. If the key given with del() function does not exist in the dictionary Python will display an error message.

Syntax-2

<dictionary name>.pop(<key>)

Example

cricket.pop(2)

This example will delete that entry from the dictionary whose key is 2. After deleting the entry it will return the value deleted from the dictionary. If the key given with pop() function does not exist in the dictionary Python will display an error message.

6) Checking existing of key

The membership operator ‘in’ and ‘not in’ can be used with the Dictionary also. These opertor be used to check for existence of ‘keys’ in the dictionary. They check existing of key only not for ‘values’

Syntax

<key> in <Dictionary name>

<key> not in <Dictionary name>

Example

if rno in student:

print(student[rno])

else:

print(“Record does not exist”)

Write a program to input key for a dictionary of cricketer’s name. Check whether that key exist in the dictionary or not. If the key exist in the dictionary then give user a choice of deleting or updating that element.

cricker={1: “Sachin”, 2: “Dhoni”, 3:”Virat”, 4: “Rohit”, 5: “Rahane”}

c=int(input(“Enter a key: “))

if c in cricket:

         print(“Press 1 for Deleting the element”)

         print(“Press 2 for Updating the element”)

        ch=int(input(“Enter your choice…: “))

          if ch==1:

                 print(“Deleted value is: “, cricket[c])

                 del cricket[c]

            else:

                    print(“Old Name:”, cricket[c])

                    nm=input(“Enter new Cricketer’s Name:”)

                    cricket[c]=nm

       print(“Final Dictionary Values are…”)

       for c in cricket:

                     print(c, cricket[c])

else:

         print(“Key does not exist”)

For Live Class Subscribe Our Youtube channel Link is given below-

https://www.youtube.com/@olevelguruji

Nested Dictionary python

We can add Dictionaries as values inside a Dictionary. Storing Dictionary inside Dictionary is called Nested Dictionary. Internal Dictionary can be used only as value inside External Dictionary and not as key.

Syntax

<dictionary name>= {<key>: {<key>: <value>,..)….}

Example

student={1: {‘name’:”Gagan”, ‘mark’:76}, 2: {‘name’: “Palak”, ‘mark’:82), 3: {‘name’:”Reena”, ‘mark’:69}}

I hope you will understand the blog Python Dictionary operations very well.

Also Check Our Latest Upload

What is a dictionary in Python?

tuple operations in python with examples

 

Leave a Comment