Lecture Slides for
PYTHON
PROGRAMMIN
G
Prof. Siddharth Kumar
Assistant Professor
School of Computer Science Engineering
Sandip University
Sijoul, Madhubani
Bihar
UNIT - 3
DICTIONARY
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered*, changeable and do
not allow duplicates.
As of Python version 3.7, dictionaries are ordered. In Python 3.6
and earlier, dictionaries are unordered.
Dictionaries are written with curly brackets, and have keys and
values:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
OUTPUT:- {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
3
DICTIONARY
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
OUTPUT:- Ford
Duplicate values will overwrite existing values:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
OUTPUT:- 2020
4
DICTIONARY
To determine how many items a dictionary has, use
the len() function:
print(len(thisdict))
The values in dictionary items can be of any data type:
thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
The dict() Constructor
It is also possible to use the dict() constructor to make a
dictionary.
thisdict = dict(name = "John", age = 36, country = "Norway")
print(thisdict)
5
DICTIONARY
You can access the items of a dictionary by referring to its key name, inside
square brackets:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
There is also a method called get() that will give you the same result:
x = thisdict.get("model")
Get Keys
The keys() method will return a list of all the keys in the
dictionary.
x = thisdict.keys()
Get Values
The values() method will return a list of all the values in the
dictionary.
x = thisdict.values()
6
DICTIONARY
Get Items
The items() method will return each item in a dictionary, as tuples
in a list.
Example
Get a list of the key:value pairs
x = thisdict.items()
Change Values
You can change the value of a specific item by referring to its key
name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
7
DICTIONARY
Update Dictionary
The update() method will update the dictionary with the items
from the given argument.
The argument must be a dictionary, or an iterable object with
key:value pairs.
Example :
Update the "year" of the car by using the update() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"year": 2020})
8
DICTIONARY
Removing Items:
The pop() method removes the item with the specified key name.
Thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
Output:- {'brand': 'Ford', 'year': 1964}
The popitem() method removes the last inserted item (in
versions before 3.7, a random item is removed instead):
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
9
DICTIONARY
The del keyword removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
The clear() method empties the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)
10
DICTIONARY METHODS
clear(): Removes all the elements from the dictionary
copy(): Returns a copy of the dictionary
get(): Returns the value of the specified key
items(): Returns a list containing a tuple for each key value pair
keys(): Returns a list containing the dictionary's keys
pop(): Removes the element with the specified key
popitem(): Removes the last inserted key-value pair
update(): Updates the dictionary with the specified key-value pairs
values(): Returns a list of all the values in the dictionary
11
FUNCTIONS
If a group of statement is repeatedly required then it is not
recommended to write these statements everytime separately. We
have to define these statements as a single unit and we can call
that unit any number of times based on our requirement without
rewriting. This unit is called function.
The main advantage of function is code resusability and
modularity.
In other language functions are known as mehods, procedures,
subroutines, etc.
Python supports two types of functions:-
i) Built In functions: functions which are coming along with python
software automatically are called built in functions or pre defined
functions.
Eg:- id(),type(),eval(),input(), etc.
ii) User defined functions:- the functions which are developed by
programmer explicitly according to business requirements are 12
FUNCTIONS
def function_name(parameters):
type your code here;
return value_if_any;
While Creating functions we can use 2 keywords:
i) def (mandatory)
ii) return (optional)
Eg:- def hello():
print(“Good morning”)
hello()
Parameters:- These are inputs to the function. If a function contains
parameters, then at the time of calling, compulsory we should provide values
otherwise, we will get error.
def wish(name):
print(“hello”,name,”Good morning”)
wish(“Durga”)
wish(“Ravi”)
13
FUNCTIONS
Formal parameters/arguments vs Actual Parameters/Arguments:
When a function is called, the values passed to the function are known as
actual arguments. The parameters specified in the function definition are called
formal arguments. The formal arguments act as placeholders for the actual
values that will be passed to the function when it is called.
14
FUNCTIONS
15
ANONYMOUS FUNCTIONS
A lambda function is a small anonymous function.
It is an one line function. It doesn’t have any
name.
A lambda function can take any number of
arguments, but can only have one expression.
x = lambda a : a + 10
print(x(5))
x = lambda a, b : a * b
print(x(5, 6))
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
16
GLOBAL & LOCAL VARIABLES
Local Variable: A local variable is defined within a function and
can only be accessed within that function. Once the function
execution is complete, the local variable is destroyed.
Global Variable: A global variable is defined outside of any
function and can be accessed from any function within the same
module. It remains in existence for the duration of the program.
x = 10
def my_function():
# Local variable
y=5
print("Inside the function:")
print("Local variable y:", y) # Accessible
print("Global variable x:", x) # Accessible
my_function()
print("Outside the function:")
print("Global variable x:", x) # Accessible
# print("Local variable y:", y) # This would raise an error
17
GLOBAL & LOCAL VARIABLES
How to change value of global variable from a function ?
value = 10 # Global Variable
def my_function():
global value # Referring to the global variable
value = 5 # Modifying the global variable
print("Inside the function, global value:", value)
my_function()
print("Outside the function, global value:", value)
18
MODULES
A group of fuctions,variables and classes saved to a file is called module.
Every python file acts as a module.
Eg: hello.py
x=888
def add(a,b):
print("the sum is" , a+b)
def product(a,b):
print("the product is", a*b)
Here, hello module contains one variable and two functions.
If we want to use members of module in our program then we should
import that module.
import module_name
We can access members by using module name.
module_name.variable
module_name.function()
19
MODULES
test.py
import hello
print(hello.x)
hello.add(10,20)
hello.product(10,20)
Renaming a module :
import hello as hii
Print(hii.x)
Print(hii.product(20,10)
from….import: We can import particular members of module by using
from…. import.
The main advantage of this is we can access members directly without
using module name.
20
MODULES
from hello import x,add
print(x)
add(10,20)
product(10,10) => Product is not defined
We can import all members of a module as follow:-
from hello import * # * is used to indicate all
print(x)
add(10,20)
product(10,10) => Works fine
21
MODULES
Various possibilities of import:
import modulename
import module1,module2, module3
import module1 as m
import module1 as m , module2 as m2
from module1 import member1
from module1 import member1,member2
from module1 import member1 as x
from module1 import *
22
MATH MODULE
math.ceil() : Rounds a number up to the nearest integer
math.factorial() : Returns the factorial of a number
math.floor() : Rounds a number down to the nearest integer
math.gcd(): Returns the greatest common divisor of two integers
math.sqrt(): Returns the square root of a number
math.trunc(): Returns the truncated integer parts of a number
math.tan(): Returns the tangent of a number
math.sin(): Returns the sine of a number
math.cos(): Returns the cosine of a number
math.pow(): Returns the value of x to the power of y
23
MATH MODULE
math.e : Returns Euler's number (2.7182...)
math.inf : Returns a floating-point positive infinity
math.nan : Returns a floating-point NaN (Not a Number) value
math.pi : Returns PI (3.1415...)
math.tau : Returns tau (6.2831...)
24
RANDOM MODULE
randrange() : Returns a random number between the given range.
randint() : Returns a random number between the given range.
choice() : Returns a random element from the given sequence.
random() : Returns a random float number between 0 and 1.
shuffle() : Takes a sequence and returns the sequence in a random
order.
25
TIME MODULE
The time module in Python provides various time-related
functions. Here’s a quick overview of its main features:
Importing the Module
To use the time module, you first need to import it:
import time
time.time(): Returns the current time in seconds since the Epoch
(January 1, 1970).
current_time = time.time()
print("Current time in seconds since the Epoch:", current_time)
time.sleep(seconds): Pauses the program for the specified
number of seconds.
print("Sleeping for 2 seconds...")
time.sleep(2)
print("Awake!")
time.localtime(): Returns the local time as a struct_time object.
local_time = time.localtime()
print("Local time:", local_time)
26
THE
END
SEE YOU IN UNIT 4 SOON..
27