Python Unit-3
Python Unit-3
UNIT - 3
{FUNCTION AND DICTIONARY}
Some unavoidable reasons that forces to apply function while developing a large
program or software.
1. Customized or user-defined function allows you to write a block of code once and use
it multiple times. You only need to write and debug the code once. This avoids the
repetition of that common code and hence also saves your lots of time.
2. Writing user-defined function can make your code easier to read and understandable.
3. It is very easier to test and debug a large program or software, if we are using the
idea of customized/user-defined function.
5. Function manages the inputs and outputs in computer programs. Python programming
language is designed to work on large scale of data and idea of function is an effective
way to manage and transform such huge amount of data.
Types of Functions:
A function is broadly classified into two major categories.
1. Standard Library (Inbuilt/Pre-defined/Readymade) Functions
2. Customized/ User-defined Functions
2. User–Defined Functions:
In Python, user-defined function is a self-contained block or group of related
statements/instructions that performs a specific task.
Function provides the idea of high degree of reusability of common code.
1
PYTHON PROGRAMMING BCA - 3001
Such kind of function is required as per the demands of our program. Use of such kind of
function avoids the repetition of same code and utilizes the idea of reusability of that
same code wherever applicable in our program.
Actual Parameters
Formal Parameters
def Function_Name(List_of_Parameters):
Statement1
Statement2
Statement3
------------- Function Body
-------------
StatementN
2
PYTHON PROGRAMMING BCA - 3001
Example: Write a program that prints a message “WELCOME TO THE WORLD OF PYTHON
PROGRAMMING” through user-defined function.
CASE-1:
def display():
print(“DEAR ALOK, WELCOME TO THE WORLD OF PYTHON PROGRAMMING.”)
CASE-2:
def display():
str1 = input(“PLEASE ENTER YOUR NAME: ”)
print(“DEAR”, str1, “,”, “WELCOME TO THE WORLD OF PYTHON PROGRAMMING.”)
OUTPUT:
PLEASE ENTER YOUR NAME: ALOK
DEAR ALOK, WELCOME TO THE WORLD OF PYTHON PROGRAMMING.
CASE-3:
def display(str2):
str1 = input(“PLEASE ENTER YOUR NAME: ”)
print(“DEAR”, str1,”,”, str2)
OUTPUT:
PLEASE ENTER THE MESSAGE THAT YOU WANT: WELCOME TO THE WORLD OF PYTHON PROGRAMMING.
PLEASE ENTER YOUR NAME: ALOK
DEAR ALOK, WELCOME TO THE WORLD OF PYTHON PROGRAMMING.
sum = 0
for i in range(50, 76):
sum = sum + i
3
PYTHON PROGRAMMING BCA - 3001
sum = 0
for i in range(90, 101):
sum = sum + i
print(“SUM OF NUMBERS FROM 90 TO 100 = ”, sum)
sum = 0
for i in range(125, 141):
sum = sum + i
print(“SUM OF NUMBERS FROM 125 TO 140 = ”, sum)
OUTPUT:
SUM OF NUMBERS FROM 1 TO 25 = 325
SUM OF NUMBERS FROM 50 TO 75 = 1625
SUM OF NUMBERS FROM 90 TO 100 = 1045
SUM OF NUMBERS FROM 125 TO 140 =
OUTPUT:
SUM OF NUMBERS FROM 1 TO 25 = 325
SUM OF NUMBERS FROM 50 TO 75 = 1625
SUM OF NUMBERS FROM 90 TO 100 = 1045
SUM OF NUMBERS FROM 125 TO 140 =
The parameters passing in function definition, which have the responsibility to accept values
coming from actual parameters are called as formal parameters.
4
PYTHON PROGRAMMING BCA - 3001
Tip: The return statement without a value is equivalent to return ‘None’. Where ‘None’ is a
special type in Python that represents nothingness.
CASE-2:
def Absolute_Value(num):
if(num>=0):
return num
else:
return –num
n1 = int(input(“PLEASE ENTER AN INTEGER NUMBER: ”))
n2 = int(input(“PLEASE ENTER AN INTEGER NUMBER: ”))
print(“ABSOLUTE VALUE = ”, Absolute_Value(n1))
print((“ABSOLUTE VALUE = ”, Absolute_Value(-n2))
Example-2: To Find And Print The Maximum And Minimum Value Between Two Numbers
CASE-1:
def Max_Value(a, b):
if(a>b):
return a
elif(b>a):
return b
else:
print(a, “ AND ”, b, “ ARE EQUAL”, )
x = int(input(“PLEASE ENTER FIRST NUMBER: ”))
y = int(input(“PLEASE ENTER SECOND NUMBER: ”))
CASE-2:
def Min_Value(a, b):
if(a<b):
return a # Returning Minimum Value ‘a’ if a is less than b
elif(b<a):
return b # Returning Minimum Value ‘b’ if b is less than a
else:
print(a, “ AND ”, b, “ ARE EQUAL”, )
x = int(input(“PLEASE ENTER FIRST NUMBER: ”))
y = int(input(“PLEASE ENTER SECOND NUMBER: ”))
5
PYTHON PROGRAMMING BCA - 3001
Example-3: To Compute And Print The Factorial Value of A Positive Number Input By User
def Cal_Facto(n):
if(n == 0):
return 1
elif(n < 0):
return n
else:
f=1
for i in range(1, n+1):
f = f*i
return f # Returning The Calculated Factorial Value ‘f’ To The Function Call
Example-2:
def Compute(n):
return n*n, n*n*n # Returning Multiple Values n*n, n*n*n To Function Call
Example-3:
def Arithmetic_Compute(x, y): # Function Header
return x+y, x-y, x*y, x/y, x%y # Returning Multiple Values To Function Call
6
PYTHON PROGRAMMING BCA - 3001
Example:
def sum(x, y):
add = x + y # WHERE ‘add’ IS A LOCAL VARIABLE
return add
print(“THE SUM OF TWO NUMBERS = ”, sum(10, 20))
Example-1:
def sum(x, y):
add = x + y # WHERE ‘add’ IS A LOCAL VARIABLE
return add
Example-2:
def fun1():
x = 10 # WHERE ‘x’ IS A LOCAL VARIABLE
print(“VALUE OF ‘x’ INSIDE FUNCTION = ”, x)
x = 20 # Global Variable
fun1() # Function Call
print(“VALUE OF ‘x’ OUTSIDE THE FUNCTION = ”, x)
OUTPUT:
VALUE OF ‘x’ INSIDE FUNCTION = 10
VALUE OF ‘x’ OUTSIDE THE FUNCTION = 20
7
PYTHON PROGRAMMING BCA - 3001
Example: Consider the following code snippet clarifying the scope of local variable
def Local_Scope():
q = 10 # Local Variable
print(“THE VALUE OF LOCAL VARIABLE q = ”, q)
OUTPUT:
THE VALUE OF LOCAL VARIABLE q = 10
Example:
def Sample():
print(s) # Using Global Variable ‘s’ In The Local Scope of The Function Sample()
Example:
def Sample();
s=“Don’t Underestimate The Commercial Market of JAVA” # Local Variable Named As ‘s’
print(s)
OUTPUT:
Don’t Underestimate The Commercial Market of JAVA
JAVA IS STILL ALIVE…..
8
PYTHON PROGRAMMING BCA - 3001
OUTPUT:
THE VALUE OF ‘a’ INSIDE THIS FUNCTION = 30
THE VALUE OF ‘a’ OUTSIDE OF THIS FUNCTION = 20
CLARIFICATION:
In the above program, we have assigned value 20 to the global variable ‘a’ defined outside of
the function definition display(). Suppose a programmer uses the same variable name ‘a’
inside the function definition but now he/she wants to modify the actual value of global
variable ‘a’ through changing the value of local variable ‘a’ inside the function definition
display(). But how will you do that?
OUTPUT:
THE VALUE OF ‘a’ INSIDE THIS FUNCTION = 30
THE VALUE OF ‘a’ OUTSIDE OF THIS FUNCTION = 30
Positional Arguments:
Suppose if there are more than one parameter, then how does Python decide which argument
in the function call statement has to be assigned to which formal parameter in function
definition?
This is simply done by assigning the order of positions of arguments. That means the first
argument in function call statement is assigned to first formal parameter listed in function
definition and so on. This style of matching up arguments and parameters is called as
positional arguments.
Example:
CASE-1: Now try to understand the following scenario.
def display(name, age):
print(“Name = ”, name, “\t”, “Age = ”, age)
9
PYTHON PROGRAMMING BCA - 3001
Remarkable Tip: Python interpreter will show an error when an incorrect number of
arguments are passed to the function call. Hence arguments must be matched with
corresponding parameters in order, number and type in function definition.
Lambda Function:
A Lambda function is named after Greek letter λ(lambda). A Lambda function is also known
as anonymous function. That means the function is without a name. The lambda keyword is
used to define an anonymous function in Python. Such kind of function is not bound to a
name. Such functions only have a code to execute that which is associated with them.
10
PYTHON PROGRAMMING BCA - 3001
Example-1: Suppose we want to calculate the cube of a positive number, then we have two
cases:
CASE-1: calculate the cube of a positive number using normal user-defined function
def cube(n):
return n*n*n
print(cube(5)) # Display The Cubic Value of 5 By Calling The lambda Function cube(5)
Clarification: The statement cube = lambda n: n*n*n creates a lambda function called cube,
which takes a single argument and returns the cube of a number 5.
Tips:
1. A lambda function does not contain a return statement.
2. A lambda function contains only a single expression rather than a block of statements
as a body.
3. A lambda function can take any number of arguments.
Example-2:
add = lambda a : a+10
print(add(5)) #Displaying Updated Value of ‘a’ By Calling The lambda function add(5)
OUTPUT: 15
Example-3:
mul = lambda a, b : a*b
print(mul(5,6)) #Displaying Product Value of ‘a*b’ By Calling lambda function mul(5,6)
OUTPUT: 30
Example-4:
add = lambda a, b, c : a+b+c
print(add(1,5,8)) #Displaying Result of (a+b+c) By Calling lambda function add(1,5,8)
OUTPUT: 14
11
PYTHON PROGRAMMING BCA - 3001
Concept of Recursion:
Recursion is a powerful technique for writing a complicated algorithm in an easy way.
According to this technique, a problem is defined in terms of itself. Such problem is solved by
dividing it into smaller problems, which are similar in nature to the original problem. These
smaller problems are solved and their solutions are applied to get the final solution of our
original problem.
Recursive Function:
The function that calls itself (inside function body) again and again is known as a recursive
function. Before writing a recursive function for a problem, we should pay attention towards
the following two major aspects.
1. We should be able to define the solution of the problem in terms of a similar type of
smaller problem. At each step, we get closer to the final solution of our original problem.
2. There must be a terminating condition (Base Case) to stop the recursion.
12
PYTHON PROGRAMMING BCA - 3001
Example-1: Write a recursive function that compute and display the result of ab (a raised to
the power b).
def power(base, exponent):
if(exponent == 0):
return 1
if(exponent == 1):
return base
if(exponent > 1):
return (base*pow(base, exponent-1)) # Recursive Function Call
print(“RESULT OF ”, base, “TO THE POWER ”, exponent, “ = ”, power(base, exponent)) # Function Call
OUTPUT:
ENTER THE VALUE OF BASE: 2
ENTER THE VALUE OF EXPONENT: 5
RESULT OF 2 TO THE POWER 5 = 32
Example-2: Write a recursive function that computes and displays the factorial value of a
positive number.
def rec_facto(n):
f=1
if(n == 0):
return 1
if(n == 1):
return n
if(n > 1):
return (n*rec_facto(n-1)) # Recursive Function Call
OUTPUT:
ENTER A POSITIVE INTEGER NUMBER: 3
FACTORIAL VALUE OF 3 = 6
13
PYTHON PROGRAMMING BCA - 3001
14
PYTHON PROGRAMMING BCA - 3001
Example-3: Write a recursive function that generate and display the Fibonacci series of terms
n, if the total number of terms n is given by user.
def rec_fibo(n):
if(n <= 1): # Base Case
return n
else:
return (rec_fibo(n-1) + rec_fibo(n-2)) # Recursive Function Call
OUTPUT:
ENTER NUMBER OF TERMS AS POSITIVE INTEGER NUMBER: 6
Fibonacci Series:
0
1
1
2
3
5
Example-4: Write a recursive function that calculate and display the sum of first n-natural
numbers, if the total number of terms n is given by user.
def sum_nums(n):
If(n == 1): # Base Case
return 1
return n + sum_nums(n - 1) # Recursive Function Call
Example-5: Write a recursive function that calculate and display the least common multiple
(LCM) of two numbers, if such two numbers are given by the user.
def LCM(x, y):
z=x%y
if z == 0: # Base Case
return x
return x * LCM(y, z) / z # Recursive Function Call
print("The least common factor is: ", LCM(4, 16)) # Displaying LCM of Two Numbers By Function Call
15
PYTHON PROGRAMMING BCA - 3001
Example-6: Write a recursive function that calculate and display the sum of digits of a
number, if that number is given by the user.
def sum_digits(n):
if(n == 0): # Base Case
return 0
else :
return int(n % 10) + sum_digits(int(n / 10)) # Recursive Function Call
Example: Write a function that can accept or pass ‘n’ number of non-keyword variable length
arguments to calculate the sum of ‘n’ numbers.
def Compute_Sum(*args):
s=0
print(“The Numbers Are As Follows:”)
for num in args:
print(num, end=’ ’)
s = s + num
return s
total = Compute_Sum(10, 20, 30, 40) # Calling Function By Passing 4 Non-Keyword Arguments
print(‘Sum = ’, total)
16
PYTHON PROGRAMMING BCA - 3001
OUTPUT:
The Numbers Are As Follows:
10, 20
Sum = 30
Syntax:
def func_name(**kwargs):
statement-1
statement-2
statement-3
-------------
-------------
func_name(variable_name1 = value1, ……..) # Function Call By Passing Keyword Arguments
OUTPUT:
{‘Country’: ‘India’, ‘Population’: 1000000000}
17
PYTHON PROGRAMMING BCA - 3001
1. Write a function that accepts a number of n-digits, reverse all digits of that number and
finally check and display whether this number is a Palindrome number or not.
A Palindrome number is a number that remains the same even if that number is inverted.
Example: 121, 11, 414, 1221, 74747 are the Palindrome numbers.
2. Write a function that accepts a string, reverse all characters of that string and finally check
and display whether that string is a Palindrome string or not.
A Palindrome string is a string that remains the same even if the letters of that string are
inverted (reversed).
Example: MOM, MADAM, DAD, ADDA, REFER are the Palindrome string.
JAVATPOINT, PROGRAM, JAVA are not the Palindrome string.
CASE-1:
def String_Palindrome(s):
return s == s[::-1]
# Driver code
s = "malayalam"
ans = String_Palindrome(s)
if(ans):
print("YES", s, "IS A PALINDROME STRING")
else:
print("NO", s, "IS NOT A PALINDROME STRING")
18
PYTHON PROGRAMMING BCA - 3001
CASE-2:
x = "malayalam"
w = ""
for i in x:
w=i+w
if (x == w):
print("YES", x, "IS A PALINDROME STRING")
else:
print("NO", x, "IS NOT A PALINDROME STRING")
3. Write a function that accepts a number of n-digits, now check and display whether this
input number is an Armstrong Number or not.
INPUT: n = 153 [Other Armstrong Numbers: 370, 371, 407, 1634(100 To 2000)]
CHECK: Sum = 13 + 53 + 33 = 153,
Since n = Sum = 153, hence ‘n’ is an Armstrong Number.
if(temp == sum):
print(temp)
start = 100
end = 2000
4. Write a function that accepts number of terms from user to generate Fibonacci Series.
If very first two terms are initially given by user in the program.
def gen_fibo_series(n):
f1, f2 = 0, 1
print(f1, “ ”, f2)
count = 3
while(count <= n):
f3 = f1 + f2
print(f3, end=' ')
f1 = f2
f2 = f3
num = int(input(“PLEASE ENTER NUMBER OF TERMS: ”))
gen_fibo_series(num) # Calling The Function
19
PYTHON PROGRAMMING BCA - 3001
5. Write a function that accepts a positive number n, if n is given by user. Now display table
of that number n in the following format.
INPUT: n = 5
Display: 5X1=5
5 X 2 = 10
5 X 3 = 15
------------
------------
5 X 10 = 50
def Display_Table(n):
i=1
while(i <=10):
print(n, “X”, i, “=”, n*i)
i+=1 # Increment The Value of Counting Variable i
# Process To Check And Print Grade As Per The Percentage Criteria Specified
if(percentage>60 and percentage<=70)
print(“Grade-D”)
if(percentage>70 and percentage<=80)
print(“Grade-C”)
if(percentage>80 and percentage<=90)
print(“Grade-B”)
if(percentage>90 and percentage<=100)
print(“Grade-A”)
20
PYTHON PROGRAMMING BCA - 3001
21
PYTHON PROGRAMMING BCA - 3001
9. Write a function that accepts a list of n-numbers and perform the following tasks:
a. Linear Search
b. Binary Search
#Function To Perform Binary Search
def binary_search(list, item):
low = 0
high = len(list)-1
while low <= high:
mid = (low + high)//2
guess = list[mid]
if guess == item:
return mid
if guess > item:
high = mid - 1
else:
low = mid + 1
return None
#Main Program
list = [] # Creating An Empty List Named list
x = int(input("Enter the number of elements: "))
22
PYTHON PROGRAMMING BCA - 3001
For example, to look up Adam’s phone number we are just interested in his phone
number from the phonebook and don’t so much concern about the location of that
phone number in the phonebook.
Introduction To Dictionary:
A dictionary is a collection that stores values along with associated unique keys. The
sequences of such keys and values pairs are separated by commas(,). Such pairs are
sometimes called items/entries. All items are enclosed within curly brackets{}. A colon(:)
sign is used to associate a value to its respective unique key.
-------------------------------------------------------
-------------------------------------------------------
Example:
Consider a dictionary named ‘Phone_Book’ that contains phone numbers of some persons.
23
PYTHON PROGRAMMING BCA - 3001
Tips:
1. Keys are like an index operator in a dictionary.
2. A key can be of any type.
3. A dictionary does not contain any duplicate keys.
4. Dictionary is a mapping of unique keys to their respective associated values, which means
each unique key is mapped to its only single value.
5. A dictionary is a collection of items/entries that are changeable and ordered (now new
version 3.7 and onwards a dictionary items are ordered except version 3.6 and earlier)
6. Python uses curly braces for both dictionary and set. Therefore to create an empty
dictionary, we must have to use {} or dict() function and for creating an empty set, we must
have to use set() function.
Creating Dictionary:
We can create a dictionary as following as:
1. Creating An Empty Dictionary:
We can create an empty dictionary by the two ways:
(a) D1 = {} # Creating An Empty Dictionary ‘D1’
print(D1)
print(type(D1)) # Displaying The Data Type of ‘D1’
OUTPUT:
{} An Empty Dictionary
<class ‘dict’>
(b) D1 = dict() # Creating An Empty Dictionary ‘D1’ Through Built-In Function dict()
print(D1)
OUTPUT:
{} An Empty Dictionary
24
PYTHON PROGRAMMING BCA - 3001
print(Phone_Book)
OUTPUT: {“Amit” : 8764557863, “Sumit” : 6294335318, “Alok” : 7965342217}
print(Employee_Info)
OUTPUT: {“Name” : “Jhony”, “Age” : 40, “Address” : “W-1, Green City”}
(b) Method-2:
Employee_Info = {} # Creating An Empty Dictionary Named ‘Employee_Info’
Employee_Info[“Name”] = “Aniket”
Employee_Info[“Age”] = 30
Employee_Info[“Address”] = “Street-5, Robin Tower, The Dream City”
print(Employee_Info)
OUTPUT:
{“Name” : “Aniket”, “Age” : 30, “Address” : “Street-5, Robin Tower, The Dream City”}
(c) Method-3:
Employee_Info = dict(Name = ‘Sachin’, Age = 28, Address = ‘Sector-15, Kinetic Road’)
print(Employee_Info)
OUTPUT:
{‘Name’ : ‘Sachin’, ‘Age’ : 28, ‘Address’ : ‘Sector-15, Kinetic Road’}
(d) Method-4:
print(dict([(“Name”, “Sachin”), (“Age”, 28), (“Address”, “Sector-15, Kinetic Road”)]))
OUTPUT:
{‘Name’ : ‘Sachin’, ‘Age’ : 30, ‘Address’ : ‘Sector-15, Kinetic Road’}
25
PYTHON PROGRAMMING BCA - 3001
Tip: If a key is already present in an existing dictionary, then it replaces the old value for this
key as mentioned with the new value added.
Example:
# Creating A Dictionary Named ‘Phone_Book’
Phone_Book = {“Amit” : 8764557863, “Sumit” : 6294335318, “Alok” : 7965342217}
OUTPUT:
{“Amit” : 6325568345, “Sumit” : 6294335318, “Alok” : 7965342217}
Example:
# Creating A Dictionary Named ‘Phone_Book’
Phone_Book = {“Amit” : 8764557863, “Sumit” : 6294335318, “Alok” : 7965342217}
print(Phone_Book[“Sumit”])
OUTPUT: 6294335318
Tip: If a key is not present in an existing dictionary, then Python interpreter raises or throws
an error.
26
PYTHON PROGRAMMING BCA - 3001
Example:
# Creating A Dictionary Named ‘Phone_Book’
Phone_Book = {“Amit” : 8764557863, “Sumit” : 6294335318, “Alok” : 7965342217}
print(Phone_Book[“Johnson”])
Example:
CASE-1:
Grades = {“Tanmay” : “A”, “Chinmay” : “B”, “Anay” : “C”, “Manmay” : “D”}
for key in Grades:
print(key, “:”, Grades[key])
OUTPUT:
Tanmay : A
Chinmay : B
Anay : C
Manmay : D
CASE-2:
Grades = {“Tanmay” : “A”, “Chinmay” : “B”, “Anay” : “C”, “Manmay” : “D”}
for key in Grades.keys():
print(key, “ ”, Grades.get(key, 0))
OUTPUT:
Tanmay : A
Chinmay : B
Anay : C
Manmay : D
27
PYTHON PROGRAMMING BCA - 3001
Formatting Dictionary:
The % operator is used to substitute values from a dictionary into a string by a name.
Example:
Items[“LAPTOP”] = “Lenovo”
Items[“COUNT”] = 500
print(Items) # Displaying Dictionary Named Items
# Now We Want To Access The Values of LAPTOP And COUNT from dictionary ‘Item’ And
# Then Use Such Values To Make A Meaningful Sentence Formatted As:
We WANT TO PURCHASE 500 Lenovo LAPTOPS For OUR BUSINESS PURPOSE.
P = “We WANT TO PURCHASE %(COUNT)d %(LAPTOP)s LAPTOPS For OUR BUSINESS PURPOSE.” %Items
OUTPUT: We WANT TO PURCHASE 500 Lenovo LAPTOPS For OUR BUSINESS PURPOSE.
Example:
#Creating Two Dictionaries With Items (Student Names, Roll Numbers)
Student_Info = {“Abodh” : 10, “Nibodh” : 11, “Subodh” : 12}
Student_Details = {“Abodh” : 10, “Nibodh” : 11, “Pramod” : 13}
print(Student_Info == Student_Details)
output: False
print(Student_Info != Student_Details)
output: True
28
PYTHON PROGRAMMING BCA - 3001
3. values(): This method returns a sequence of all values corresponds to all existing keys.
Example:
ASCII_CODES = {“A” : 65, “B” : 66, “C” : 67, “D” : 68}
print(ASCII_CODES)
OUTPUT: {“A” : 65, “B” : 66, “C” : 67, “D” : 68}
4. clear(): This method is used to delete or remove all items or entries of a dictionary.
Example:
ASCII_CODES = {“A” : 65, “B” : 66, “C” : 67, “D” : 68}
5. get(key): This method is used to return a value corresponds to a specific key existing in
the dictionary.
Example:
Temperature = {“Mumbai” : 35, “Delhi” : 40, “Chennai” : 45, “Kanpur” : 42}
6. pop(key): This method is used to return a value corresponds to a key removed from the
dictionary.
Example:
Temperature = {“Mumbai” : 35, “Delhi” : 40, “Chennai” : 45, “Kanpur” : 42}
29
PYTHON PROGRAMMING BCA - 3001
9. update(): This method updates an existing dictionary with new items added
CASE-1:
Example:
Temperature1 = {“Mumbai” : 35, “Delhi” : 40, “Chennai” : 45, “Kanpur” : 42}
Temperature2 = {“Lucknow” : 38, “Noida” : 41, “Bhopal” : 39, “Chandigarh” : 35}
Temperature1.update(Temperature2)
print(Temperature1)) # Display Updated Temperature1 By Adding Items of Temperature2
OUTPUT:
{“Mumbai” : 35, “Delhi” : 40, “Chennai” : 45, “Kanpur” : 42, “Lucknow” : 38, “Noida” : 41, “Bhopal” : 39, “Chandigarh” : 35}
30
PYTHON PROGRAMMING BCA - 3001
Nested Dictionary:
A dictionary defined within a dictionary is called as a nested dictionary. It is needed
immensely when we want to get fruitful detailed information.
Now let’s try to understand about the nested dictionary by the following example.
Example: Consider a dictionary of Indian Cricket Players with some information about them.
Players = {“Virat” :{“ODI” : 7212, “Test” : 5000}, “Sachin” :{ “ODI” : 18426, “Test” : 15921}}
OUTPUT: 7212
OUTPUT: 5000
OUTPUT: 18426
OUTPUT: 15921
Players = {“Virat” :{“ODI” : 7212, “Test” : 5000}, “Sachin” :{ “ODI” : 18426, “Test” : 15921}}
We can traverse/access each and every items of nested dictionary by the following ways.
Method-1:
OUTPUT:
Sachin
{“Test” : 15921, “ODI” : 18426}
Virat
{“Test” : 5000, “ODI” : 7212}
Method-2:
31
PYTHON PROGRAMMING BCA - 3001
OUTPUT:
Player Name: Sachin
Runs Scored In ODI : 18426
Runs Scored In Test : 15921
Method-3:
OUTPUT:
Sachin
ODI : 18426
Test : 15921
Virat
ODI : 7212
Test : 5000
P = {0: -2, 2: 1, 3: 3}
Compute_Poly(P, 2)
32
PYTHON PROGRAMMING BCA - 3001
1. WAP to calculate the total number of even and odd numbers in a list and return the result
in form of dictionary.
def dict_even_odd(l):
d = dict()
d['even'] = 0
d['odd'] = 0
for i in l:
if i%2 == 0:
d['even'] += 1
else:
d['odd'] += 1
return d
2. Write a function to calculate total number of postive and negative numbers in a list and
return the result in form of dictionary
def dict_Pos_Neg(l):
d = dict()
d['positive'] = 0
d['negative'] = 0
for i in l:
if i > 0:
d['positive'] += 1
elif i < 0:
d['negative'] += 1
return d
3. WAP to print the square of the first ‘N’ natural numbers in form of dictionary.
def dict_square(n):
d = dict()
for i in range(1,n+1):
d[i] = i**2
return d
n = int(input('Enter the number: '))
print(dict_square(n)) # Function Call
4. Write a function histogram that takes a string as parameter and prints the frequency of
characters contained in it in form of dictionary.
CASE-1:
def histogram(s):
d = dict()
33
PYTHON PROGRAMMING BCA - 3001
for c in s:
if c not in d:
d[c] = 1
else:
d[c] += 1
return d
CASE-2:
def histogram(s):
d = dict()
for c in s:
if c not in d:
d[c] = 1
else:
d[c] = d.get(c, 0) + 1 # Using get() Method
return d
6. WAP that accepts a nested dictionary of 4-Indian Cricket Players having scores in different
formats such as One-Day International, T-20 and Test matches. Now calculate and print the
total score of each player in all formats of Cricket.
34
PYTHON PROGRAMMING BCA - 3001
7. Consider the following dictionary named car_sales, which has sales of multiple cars in
different states.
Now write functions that perform the following tasks:
a. Display sales statewise and total sales of 4 states
b. Display overall sales of each automobile company (Hyundai, Ford, Tata)
c. Calculate and display the average sales of cars of all four states (UP, Maharashtra, Delhi,
Haryana)
d. Calculate and display the average sales of automobiles companies (Hyundai, Ford, Tata)
car_sales = {
"UP":{"Hyundai": 6000, "Ford": 5000, "Tata":8000},
"Delhi":{ "Hyundai": 7000, "Ford": 6000, "Tata":10000},
"Maharastra":{ "Hyundai": 8000, "Ford": 4000, "Tata":12000},
"Haryana":{ "Hyundai": 4000, "Ford": 8000, "Tata":15000}
}
#Function To Display Sales Statewise And Total Sales
def sales_state_wise(car_sales):
for state in car_sales:
print("Sales in", state)
for car in car_sales[state]:
print(car, ":", car_sales[state][car])
print()
35
PYTHON PROGRAMMING BCA - 3001
# Main Program
sales_state_wise(car_sales) # Function Call1
overall_sales(car_sales) # Function Call2
average_sales(car_sales) # Function Call3
average_sales_car(car_sales) # Function Call4
36