Working With Dictionaries In Python Programing - Coderz*United

Working With Dictionaries In Python Programing




 

Working with Dictionaries

After the basics of dictionaries, let us discuss various operations that you can perform  on dictionaries such as adding elements to dictionaries, updating and deleting elements of dictionaries. This section is dedicated to the same.

Multiple ways of Creating Dictionaries

 1. Initializing dictionary- all the key:value pairs of a dictionary are written collectively

s={'Name': 'Anand', 'AdmnNo': 2367, 'Class': 11, 'Per': 92.7} 


2. Adding key:value pairs to an empty dictionary 

s={ } 

s=dict() 

s['Name']='Anand' 

s['AdmnNo']=2367 

s['Class']=11 

s['Per']=92.7 

print(s)

Out[1]: {'Name': 'Anand', 'AdmnNo': 2367, 'Class': 11, 'Per': 92.7} 


3. Creating a dictionary from name:value pairs 

(i) Specify key:value pairs as keyword arguments to dict() function

s=dict(Name='Anand',AdmnNo=2367,Class=11, Per=92.7

print(s)

Out[1]: {'Name': 'Anand', 'AdmnNo': 2367, 'Class': 11, 'Per': 92.7} 

 


(ii) Specify comma separated key:value pairs 

s=dict({'Name':'Anand','AdmnNo':2367,'Class': 11,'Per':92.7}) 

print(s) 

Out[1]: {'Name': 'Anand', 'AdmnNo': 2367, 'Class': 11, 'Per': 92.7} 


(iii) Specify keys separately and corresponding values separately 

s=dict(zip(('Name','AdmnNo','Class','Per'),('Anand',2367,11,92.7))) 

print(s) 

Out[1]: {'Name': 'Anand', 'AdmnNo': 2367, 'Class': 11, 'Per': 92.7} 


(iv) Specify key:value pairs separately in the form of sequence 

s=dict([['Name','Anand'],['AdmnNo',2367],['Class',11],['Per',92.7]])

print(s) 

Out[1]: {'Name': 'Anand', 'AdmnNo': 2367, 'Class': 11, 'Per': 92.7}


s=dict((['Name','Anand'],['AdmnNo',2367],['Class',11],['Per',92.7])) 

print(s)

Out[2]: {'Name': 'Anand', 'AdmnNo': 2367, 'Class': 11, 'Per': 92.7}

Adding elements to dictionary

New elements (key:value pair) to a dictionary using assignment as per the following Syntax. But the key being added must not exist in dictionary and must be unique. If the key already exists, then this statement will change the value of the existing key and no new entry will be added to a dictionary.

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

print(student) 

Out[2]: {'Name': 'Anand', 'AdmnNo': 2367, 'Class': 11, 'Per': 92.7} student['School']='Coderz*United' 

print(student)  

Out[2]: {'Name': 'Anand', 'AdmnNo': 2367, 'Class': 11, 'Per': 92.7, 'School': 'Coderz*United'}

Nesting Dictionaries

To add dictionaries as values inside a dictionary, sorting a dictionary inside another dictionary is called a nesting of dictionaries. But one thing you must know about nesting dictionary is that you can store a dictionary as a value only, inside a dictionary. You cannot have a key dictionary type; you know the reason-only mutable types can form the key of a dictionary

Updating/Modifying Existing Elements in a Dictionary

Updating element is similar to what we just did now. You can change the value of an existing key using assignment as per following syntax :

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

print(student)  

Out[1]: {'Name': 'Anand', 'AdmnNo': 2367, 'Class': 12, 'Per': 92.7} 

student['Class']=11      #Updated the value of the key 'Class' on the dictionary student

print(student)  

Out[2]: {'Name': 'Anand', 'AdmnNo': 2367, 'Class': 11, 'Per': 92.7} 

student['School']=None 

print(student) 

Out[3]: {'Name': 'Anand', 'AdmnNo': 2367, 'Class': 11, 'Per': 92.7, 'School': None}

But make sure that the key must exist in the dictionary otherwise a new entry will be added to the dictionary. Using this technique of adding key value pairs you can create dictionaries interactively at runtime by accepting input from user.

Deleting Elements from a Dictionary

For deleting elements from a dictionary you can use either the del statement or pop() or popitem()  functions. Here we are talking about the del statement and we shall talk about the pop() and the popitem() functions later.

del< dictionary>[< key>]

print(student

Out[1]: {'Name': 'Anand', 'AdmnNo': 2367, 'Class': 11, 'Per': 92.7, 'School': None}

del student['School'

print(student)  

Out[2]: {'Name': 'Anand', 'AdmnNo': 2367, 'Class': 11, 'Per': 92.7} 

del student['School']  

print(student

KeyError: 'School'

Checking for Existence of a Key

Usual membership operators in and not in work with dictionaries as well. But they can check for the existence of  keys only. To check for whether a value is present in a dictionary (called reverse lookup), you need to write a proper code for that.

<key>in<dictionary>

<key>not in<dictionary>

The in operator will return true if the given key is present in the dictionary, otherwise False.

The not in operator will return true if the given key is not present in the dictionary, otherwise False.


Ques: Consider already created dictionary M that stores roll numbers and marks. Write a program to input a roll number and delete it from the dictionary. Display an error message if the roll number does not exist in the dictionary ?


Pretty Printing a Dictionary

We generally use the print function to print a dictionary in Python. But if the dictionary is large then, shouldn't there be any way of appending a dictionary in a way that makes it more readable and presentable ?

Well there certainly is a way. For this you need to import json module by giving statement import json ( recall that in a program the import statement should be given before using any function of the imported package)

The function dumps() of json module as per the following syntax inside print():

 json.dumps(<dictionary name>,indent = <n>)


Ques: Program to count the frequency of  list of elements using a dictionary ?

Counting Frequency of Elements in a list using Dictionary

A dictionary uses key:value pairs to store its elements, you can use this feature effectively if you're trying to calculate the frequency of elements in a sequence such as lists. 

You can do this as:-

 1. Create an Empty dictionary

 2.Take an element from the list

 3.Check if the element exist as a key in the dictionary

If not then add {key:value} to dictionary in the form {List-element : count of List-element in List}