Sunday, 18 August 2019

How to add or delete elements in python dictionary | Dictionary in Python 3

How to add or delete elements in python dictionary | Dictionary in Python3



Adding Elements to dictionary


We can add a new key: value pair to a dictionary using assignment operator (=). The added/entered key must be unique. But if the key entered is already exists then this will change the value of existing key and no new entry would be added to dictionary.

Syntax:

Dictionary-name [key] = value

For example:

Employee = {‘name’: ‘Harsh’, ‘salary’: ‘40000’, ‘age’: ‘29’}
Employee[‘dept’] = ‘Accounts’
Employee[‘salary’] = ’20000’

Screenshot:
How to add key to dictionary example


Here we are adding a new element ‘dept: Accounts’, this would be added but ‘salary: 20000’ will not add, it will overwrite to an existing element ’salary: 40000’ to ‘salary: 20000’.

How to Create Nesting Dictionaries

We can create or add a dictionary inside a dictionary. We can store a dictionary as a value only inside a dictionary. We cannot have a key of dictionary type because the keys of a dictionary are of immutable types such as numbers or strings. A tuple can also be a key provided it contains immutable elements.

Question. Write a program to display the details of two employees with their names as key and other details as value in the form of dictionary using loop?

Answer:

Employee= {‘Harsh’: {‘age’: 25, ’salary’: 20000}, ‘Veena’: {‘age’: 35, ’salary’: 40000}}
for key in Employee:
                print (“Employee”, key, ‘:’)
                print (‘Age:’, str (Employee[key][‘age’]))
                print (‘salary:’, str (Employee[key][‘salary’]))

output:

Employee Harsh:
 Age: 25
Salary: 20000

Employee Veena:
Age: 35
Salary: 40000

Screenshot:

Example of nesting dictionary in python


Here the elements are being accessed from inner dictionaries.


Deleting Elements from a Dictionary


There are two methods for deleting elements from a dictionary.

1. To delete a dictionary element or a dictionary entry. We can use del command.

Syntax:

del dictionary-name [key]

For example:

Employee= {‘name’: ‘Harsh’, ‘age’: 25, ’salary’: 20000}
del Employee[‘age’]

Screenshot:
How to delete a key value in dictionary python

How to delete dictionary element


When you delete an element using del command, the key that you are giving must be exists in a dictionary otherwise Python raises a Key Error.


2.To delete a dictionary element or a dictionary entry. We can use pop () method.

Syntax:

 Dictionary-name. pop(key)

For example:

Employee= {‘name’: ‘Harsh’, ‘age’: 25, ’salary’: 20000}
Employee.pop(‘age’)

Screenshot:
Delete a python dictionary element with pop function


When you use pop () method to delete an element, if the key does not exist in a dictionary then Python raises a Key Error.

Checking for Existence of a key

We can use membership operators in and not in with the dictionaries as well to check the existence of a key.

Syntax:

<Key> in <dictionary-name>
<key> not in <dictionary-name>

- The in operator will return true if the given key is present in the dictionary otherwise this returns false.

- The not in operator will return true if the given key is not present in the dictionary otherwise this returns false.

For example:
How to use in operator


Remember that the operators in and not in do not apply on values of a dictionary. If you use them, it will only look for in the keys of the dictionary not values.

Customization of Printing a Dictionary

As we use print () function to print a dictionary.

For example:

BirdCount= {“Finch”:”10”,” Myna”:”13”,” Parrot”:”25”,” Peacock”:”15”}
print (BirdCount)

Output:

{“Finch”:”10”,” Myna”:”13”,” Parrot”:”25”,” Peacock”:”15”}

Here we can read and understand the key and value but if the dictionary is too large then it should not be more readable and understandable.

To make a large dictionary more readable, we need to import json module by giving statement import json. And then we can use the function dumps () of json module to print the dictionary in readable format.

Screenshot:

how to use dumps method in python


Here key value pairs in separate lines and 2 spaces in front of every line because we gave value 2 for indent (indent=2).

No comments:

Post a Comment

Recent Post

Python Project | Banking System | Project on Banking System using python

  PYTHON PROJECT Banking System import csv import pandas as pd import matplotlib.pyplot as plt import sys import datetime found=False def ne...