[go: up one dir, main page]

0% found this document useful (0 votes)
8 views26 pages

Unit 3 & 4

The document provides a comprehensive overview of dictionaries in Python, detailing their structure, creation, and various operations such as accessing, modifying, and removing elements. It also covers nested dictionaries, dictionary comprehensions, and sorting methods, along with practical exercises for application. Additionally, the document discusses Python functions, their advantages, types of arguments, and variable scopes.

Uploaded by

krashan.042732
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views26 pages

Unit 3 & 4

The document provides a comprehensive overview of dictionaries in Python, detailing their structure, creation, and various operations such as accessing, modifying, and removing elements. It also covers nested dictionaries, dictionary comprehensions, and sorting methods, along with practical exercises for application. Additionally, the document discusses Python functions, their advantages, types of arguments, and variable scopes.

Uploaded by

krashan.042732
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Dictionaries in Python (Python 3.

7)

1. Introduction to Dictionaries
1.1 What is a Dictionary?

A dictionary in Python is an ordered, mutable collection that stores data in key-value pairs. Unlike
lists or tuples, dictionaries use keys for indexing instead of numerical indices.

1.2 Why Use Dictionaries?

 Fast Data Retrieval – Lookup operations are faster than lists.


 Flexibility – Supports mixed data types.
 No Duplicate Keys – Ensures data uniqueness.
 Structured Storage – Useful for representing real-world objects.

1.3 Creating a Dictionary

Dictionaries can be created using {} (curly brackets) or the dict() constructor.

Example:

# Creating a dictionary using curly brackets

details = {"name": "Alice", "age": 25, "city": "New York"}

# Creating a dictionary using the dict() constructor

info = dict(name="Bunny", age=30, city="India")

2. Accessing Values in a Dictionary


2.1 Using Keys

We can access dictionary values using keys inside square brackets [].

Example:

details = {"name": "Alice", "age": 25, "city": "New York"}


print(details["name"]) # Output: Alice

Note: If the key does not exist, Python raises a KeyError.

2.2 Using the get() Method

The get() method retrieves a value and prevents errors if the key is missing.
Example:

print(details.get("age")) # Output: 25
print(details.get("country", "Not Available")) # Output: Not Available

2.3 Checking Key Existence

Use the in keyword to check if a key exists in a dictionary.

Example:

print("name" in details) # Output: True


print("country" in details) # Output: False

3. Working with Dictionaries

3.1 Modifying Dictionaries

#Adding a New Key-Value Pair

details["country"] = "USA"
print(details)

#Updating an Existing Value

details["age"] = 26

3.2 Removing Elements from a Dictionary

Using del Statement

del details["city"]

Using pop() Method

age = details.pop("age")
print(age) # Output: 26

3.3 Looping Through a Dictionary

Iterating Over Keys

for key in details:


print(key)

Iterating Over Key-Value Pairs


for key, value in details.items():
print(f"{key}: {value}")

3.4 Dictionary Methods

Getting Keys, Values, and Items

print(details.keys()) # Output: dict_keys(['name', 'country'])


print(details.values()) # Output: dict_values(['Alice', 'USA'])
print(details.items()) # Output: dict_items([('name', 'Alice'), ('country', 'USA')])

Clearing a Dictionary

details.clear()
print(details) # Output: {}

4. Nested Dictionaries
Dictionaries can contain other dictionaries as values.

Example:

students = {
"Alice": {"age": 22, "course": "CS"},
"Bob": {"age": 24, "course": "Math"}
}
print(students["Alice"]["course"]) # Output: CS

5. Dictionary Comprehensions (Python 3.7 Compatible)


Dictionary comprehensions provide a concise way to create dictionaries.

Example:

squares = {x: x*x for x in range(1, 6)}


print(squares) # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
6. Sorting Dictionaries (Python 3.7 Compatible)
Sorting by Keys

data = {"banana": 3, "apple": 1, "cherry": 2}


sorted_by_keys = {k: data[k] for k in sorted(data)}
print(sorted_by_keys)

Sorting by Values

sorted_by_values = {k: v for k, v in sorted(data.items(), key=lambda item: item[1])}


print(sorted_by_values)

8. Practice Exercises
8.1 Creating a Student Database

Write a program that stores student details (name, age, and course) using a dictionary and allows
updating values.

8.2 Counting Word Frequency

Write a program to count the frequency of words in a given text using a dictionary.

Example:

text = "hello world hello"


words = text.split()
frequency = {}
for word in words:
frequency[word] = frequency.get(word, 0) + 1
print(frequency) # Output: {'hello': 2, 'world': 1}
Python Functions
Functions are the most important aspect of an application. A function can be defined
as the organized block of reusable code which can be called whenever required.

Python allows us to divide a large program into the basic building blocks known as
function. The function contains the set of programming statements enclosed by {}. A
function can be called multiple times to provide reusability and modularity to the
python program.

In other words, we can say that the collection of functions creates a program. The
function is also known as procedure or subroutine in other programming languages.

Python provide us various inbuilt functions like range() or print(). Although, the user
can create its functions which can be called user-defined functions.

Advantage of Functions in Python


There are the following advantages of Python functions.

o By using functions, we can avoid rewriting same logic/code again and again in
a program.
o We can call python functions any number of times in a program and from any
place in a program.
o We can track a large python program easily when it is divided into multiple
functions.
o Reusability is the main achievement of python functions.
o However, Function calling is always overhead in a python program.

Creating a function
In python, we can use def keyword to define the function. The syntax to define a
function in python is given below.
1. def my_function():
2. function-suite
3. return <expression>

The function block is started with the colon (:) and all the same level block
statements remain at the same indentation.

A function can accept any number of parameters that must be the same in the
definition and function calling.

Function calling
In python, a function must be defined before the function calling otherwise the python
interpreter gives an error. Once the function is defined, we can call it from another
function or the python prompt. To call the function, use the function name followed by
the parentheses.

A simple function that prints the message "Hello Word" is given below.

1. def hello_world():
2. print("hello world")
3.
4. hello_world()

Output:

hello world

Parameters in function
The information into the functions can be passed as the parameters. The parameters
are specified in the parentheses. We can give any number of parameters, but we
have to separate them with a comma.

Consider the following example which contains a function that accepts a string as the
parameter and prints it.

Example 1
1. #defining the function
2. def func (name):
3. print("Hi ",name);
4.
5. #calling the function
6. func("Ayush")

Example 2
1. #python function to calculate the sum of two variables
2. #defining the function
3. def sum (a,b):
4. return a+b;
5.
6. #taking values from the user
7. a = int(input("Enter a: "))
8. b = int(input("Enter b: "))
9.
10. #printing the sum of a and b
11. print("Sum = ",sum(a,b))

Output:

Enter a: 10

Enter b: 20

Sum = 30

Call by reference in Python


In python, all the functions are called by reference, i.e., all the changes made to the
reference inside the function revert back to the original value referred by the
reference.

However, there is an exception in the case of mutable objects since the changes
made to the mutable objects like string do not revert to the original string rather, a
new string object is made, and therefore the two different objects are printed.

Example 1 Passing Immutable Object (List)


1. #defining the function
2. def change_list(list1):
3. list1.append(20);
4. list1.append(30);
5. print("list inside function = ",list1)
6.
7. #defining the list
8. list1 = [10,30,40,50]
9.
10. #calling the function
11. change_list(list1);
12. print("list outside function = ",list1);

Output:

list inside function = [10, 30, 40, 50, 20, 30]

list outside function = [10, 30, 40, 50, 20, 30]

Example 2 Passing Mutable Object (String)


1. #defining the function
2. def change_string (str):
3. str = str + " Hows you";
4. print("printing the string inside function :",str);
5.
6. string1 = "Hi I am there"
7.
8. #calling the function
9. change_string(string1)
10.
11. print("printing the string outside function :",string1)

Output:

printing the string inside function : Hi I am there Hows you

printing the string outside function : Hi I am there

Types of arguments
There may be several types of arguments which can be passed at the time of function
calling.

1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments

Required Arguments
Till now, we have learned about function calling in python. However, we can provide the
arguments at the time of function calling. As far as the required arguments are
concerned, these are the arguments which are required to be passed at the time of
function calling with the exact match of their positions in the function call and function
definition. If either of the arguments is not provided in the function call, or the position
of the arguments is changed, then the python interpreter will show the error.

Consider the following example.

Example 1
1. #the argument name is the required argument to the function func
2. def func(name):
3. message = "Hi "+name;
4. return message;
5. name = input("Enter the name?")
6. print(func(name))

Output:

Enter the name?John


Hi John

Example 2
1. #the function simple_interest accepts three arguments and returns the simple interest a
ccordingly
2. def simple_interest(p,t,r):
3. return (p*t*r)/100
4. p = float(input("Enter the principle amount? "))
5. r = float(input("Enter the rate of interest? "))
6. t = float(input("Enter the time in years? "))
7. print("Simple Interest: ",simple_interest(p,r,t))

Output:

Enter the principle amount? 10000


Enter the rate of interest? 5
Enter the time in years? 2
Simple Interest: 1000.0

Example 3
1. #the function calculate returns the sum of two arguments a and b
2. def calculate(a,b):
3. return a+b
4. calculate(10) # this causes an error as we are missing a required arguments b.

Output:

TypeError: calculate() missing 1 required positional argument: 'b'

Keyword arguments
Python allows us to call the function with the keyword arguments. This kind of function
call will enable us to pass the arguments in the random order.

The name of the arguments is treated as the keywords and matched in the function
calling and definition. If the same match is found, the values of the arguments are
copied in the function definition.

Consider the following example.

Example 1
1. #function func is called with the name and message as the keyword arguments
2. def func(name,message):
3. print("printing the message with",name,"and ",message)
4. func(name = "John",message="hello") #name and message is copied with the values Jo
hn and hello respectively

Output:

printing the message with John and hello

Example 2 providing the values in different order at the calling


1. #The function simple_interest(p, t, r) is called with the keyword arguments the order of
arguments doesn't matter in this case
2. def simple_interest(p,t,r):
3. return (p*t*r)/100
4. print("Simple Interest: ",simple_interest(t=10,r=10,p=1900))

Output:
Simple Interest: 1900.0

If we provide the different name of arguments at the time of function call, an error will
be thrown.

Consider the following example.

Example 3
1. #The function simple_interest(p, t, r) is called with the keyword arguments.
2. def simple_interest(p,t,r):
3. return (p*t*r)/100
4.
5. print("Simple Interest: ",simple_interest(time=10,rate=10,principle=1900)) # doesn
't find the exact match of the name of the arguments (keywords)

Output:

TypeError: simple_interest() got an unexpected keyword argument 'time'

The python allows us to provide the mix of the required arguments and keyword
arguments at the time of function call. However, the required argument must not be
given after the keyword argument, i.e., once the keyword argument is encountered in
the function call, the following arguments must also be the keyword arguments.

Consider the following example.

Example 4
1. def func(name1,message,name2):
2. print("printing the message with",name1,",",message,",and",name2)
3. func("John",message="hello",name2="David") #the first argument is not the keywor
d argument

Output:

printing the message with John , hello ,and David


The following example will cause an error due to an in-proper mix of keyword and
required arguments being passed in the function call.

Example 5
1. def func(name1,message,name2):
2. print("printing the message with",name1,",",message,",and",name2)
3. func("John",message="hello","David")

Output:

SyntaxError: positional argument follows keyword argument

Default Arguments
Python allows us to initialize the arguments at the function definition. If the value of
any of the argument is not provided at the time of function call, then that argument
can be initialized with the value given in the definition even if the argument is not
specified at the function call.

Example 1
1. def printme(name,age=22):
2. print("My name is",name,"and age is",age)
3. printme(name = "john") #the variable age is not passed into the function however th
e default value of age is considered in the function

Output:

My name is john and age is 22

Example 2
1. def printme(name,age=22):
2. print("My name is",name,"and age is",age)
3. printme(name = "john") #the variable age is not passed into the function however th
e default value of age is considered in the function
4. printme(age = 10,name="David") #the value of age is overwritten here, 10 will be pr
inted as age
Output:

My name is john and age is 22

My name is David and age is 10

Variable length Arguments


In the large projects, sometimes we may not know the number of arguments to be
passed in advance. In such cases, Python provides us the flexibility to provide the
comma separated values which are internally treated as tuples at the function call.

However, at the function definition, we have to define the variable with * (star) as
*<variable - name >.

Consider the following example.

Example
1. def printme(*names):
2. print("type of passed argument is ",type(names))
3. print("printing the passed arguments...")
4. for name in names:
5. print(name)
6. printme("john","David","smith","nick")

Output:

type of passed argument is <class 'tuple'>

printing the passed arguments...

john

David

smith

nick

Scope of variables
The scopes of the variables depend upon the location where the variable is being
declared. The variable declared in one part of the program may not be accessible to
the other parts.

In python, the variables are defined with the two types of scopes.

1. Global variables
2. Local variables

The variable defined outside any function is known to have a global scope whereas
the variable defined inside a function is known to have a local scope.

Consider the following example.

Example 1
1. def print_message():
2. message = "hello !! I am going to print a message." # the variable message is loc
al to the function itself
3. print(message)
4. print_message()
5. print(message) # this will cause an error since a local variable cannot be accessible
here.

Output:

hello !! I am going to print a message.

File "/root/PycharmProjects/PythonTest/Test1.py", line 5, in

print(message)

NameError: name 'message' is not defined

Example 2
1. def calculate(*args):
2. sum=0
3. for arg in args:
4. sum = sum +arg
5. print("The sum is",sum)
6. sum=0
7. calculate(10,20,30) #60 will be printed as the sum
8. print("Value of sum outside the function:",sum) # 0 will be printed
Output:

The sum is 60
Value of sum outside the function: 0

Lambda Function

Python lambda function doesn’t have any return statement.Ithas only a single expression
which is always returned by default.The Python lambda function is anonymous as it is a
function without a def keyword and name. To create a Python lambda function, we have to
use the lambda keyword.

The basic syntax of python lambda is

Lambda arguments : expression

The Python lambda function accepts any number of arguments but use only one expression.
For instance, lambda a, b: a + b. Here, a and b are the arguments accepted by the lambda
function. a + b is the expression.

Both lambda function and regular function returns the same result. However, the
regular function needs a def keyword, function name, and a return value.
Whereas, lambda function does not need any of them. By default, it returns the
expression result.
Modules & Packages

Module is a logical group of functions, classes, variables in a single python file saved
with .pyextension. In other words, we can also say that a python file is a module. We
have seen few examples of built-in modules, which are used in the program by
import statement. Python provides many built-in modules. We can also create our
own module.
A major benefit of a module is that functions, variable or objects defined in one
module can be easily used by other modules or files, which make the code re-usable.
A module can be created like any other python file. Name of the module is the same
as the name of a file. Let us create out first module- series.py.

In this module, we have created three functions- to find factorial of a number,


Fibonacci series up to given number of terms and a function to display exponential
series and it sum. After creating a file, save it with name series.py.

Our module is successfully created. Now let us test our module by importing in some
other file and check whether it is working or not. For verifying that, in a new file, two
steps are needed to be done.

1. Import the module we have created to make it accessible


2. Call the functions of that module with module name and a dot (.) symbol.

Accessing function in module created in Example 1.


Similar to the above example, we can call another function created in the module
fibonacci() by following the same process.

import Series
Series.fibonacci(2, 10)

Importing a module:

Importing is the process of loading a module in other modules or files. It is


necessary to import a module before using its functions, classes or other objects. It
allows users to reference its objects. There are various ways of importing a module.

1. using import statement


2. using from import statement
3. using from import * statement

Importing Complete module: In this method, we can import the whole module all
together with a single import statement. In this process, after importing the module,
each function (or variable, objects etc.) must be called by the name of the module
followed by dot (.) symbol and name of the function.

Syntax of function calling within module

import module
module.function_name()

Importing using from import statement: In this method of importing, instead of


importing the entire module function or objects, only a particular object needed can
be imported. In this method, objects can be directly accessed with its name.
Importing entire module using from import *: This method can be used to
import the entire module using from import * statement. Here,*represents all the
functions of a module. Like previous method, an object can be accessed directly with
its name.

Package Creation & Importing

Packages like modules are also used to organize the code in a better way. A package
is a directory which contains multiple python modules. It is used to group multiple
related python modules together. A python package in addition to modules must
contain a file called __init__.py. This file may be empty or contains data like other
modules of package.

File __init__.py

It is a file that makes the package importable. When a package is imported in a


script, this file is automatically executed. It initializes variables, objects and makes
the functions in the package accessible.

Let us create a package namedpack and within this package create two modules
first.py and second.py

The __init__.py file created is empty.


Module one contains function abc() and module two contains
function xyz().
Packages can be imported in the same way as we import
modules. The various ways in which we can import from
package are-
There are more methods to import. We have used * to import all the functions from
a module in the previous section. This method can also be used here. But by default
importing package modules using * will show error.

Standard Library Modules:

Python standard library provides number of built-in modules. They are automatically
loaded when an interpreter starts. It should be noted that before using any module,
it should be imported first. Some of the commonly used library modules are-

 sys
 os
 math
 random
 statistics

Module Attributes
There are some attributes or functions that work for every module whether it is built-
in library module or custom module. These attributes help in smooth operations of
these modules.
Some of them are explained below:

1. help () – it is a function used to display modules available for use in python or


to get help on specific module.

2. dir ()- it is a function which is used to display objects or functions present in a


specific module.Before using dir() function, module should be first imported.
3. __file__ attribute- This attribute returns the location or path of the module.

OS MODULE
This is a module responsible for performing many operating system tasks. It
provides functionality like- creating directory, removing directory, changing
directory, etc.Some of the functions in os modules are given in the table below. It
should be noted that before using these functions, the module should be imported.

SYS MODULE
This module contains various variables and functions that can manipulate python
runtime environment. Some of them are listed intable given below:
MATH MODULE
This module provides various mathematical functions and constant variables. It
includes logarithmic, trigonometric functions etc. Some of the functions are listed in
table below:
STATISTICS MODULE
This module contains various functions used in statistics. These functions are widely
used for data analysis or data science.

File Operation

Main memory is volatile in nature, hence, nothing can be stored permanently. File
handling is a very important functionality which must be provided by any language to
deal with this problem. Inputs can be taken from files instead of users, output can be
displayed and saved permanently in files which can further be accessed later and
appended or updated. All these functionalities come under file handling. Like other
languages, python also provides various built-in functions for file handling
operations.
There are two types of files supported by python- Binary and Text.

Binary files – These are the files that can be represented as 0’s and 1’s. These files
can be processed by applications knowing about the file’s structure. Image files are
example of binary files.

Text files – These files are organized as sequence of characters. Here, each line is
separated by a special end of line character. Any file handling operation can be
performed in three steps-

1. Opening a file
2. Operating on file – read, write , append etc.
3. Closing a file

1. Opening a file:
A file can be opened in a Python using built-in function open(). By default the files
are opened in read text (‘r’) file mode.
Syntax of open() function

Where,
File_name.ext - is the name of the file to be opened and ext is the extension of file.

Mode_of_operation - is the mode in which file is needed to be opened.

file – is the object returned by the function. This object can be used for further
operations on file.
The possible mode of operations in python –

2. Operating on file
There are various operations –

Reading from a file: There are many ways to read from a file. Given below are the
functions available for reading
from a file.
In the below table assume
that file is the object returned
from open() function.
Writing to a file: Similar to read operations, functions are there in python to write
data to file.

Operations on file: Python allows many other operations to be done in with files.
Listed below are some functions used for file handling.

Closing a file: After completing all the operations on file, it must be closed properly.
This step frees up the resources and allows graceful termination of file operations.

Syntax of closing a file

file.close()

Reading data from a file


There are various ways to read a file by following the steps explained in the above
section. For reading data from the file, it must be existing. Below is given the
program to read a file named “first.txt” in the directory files within the present
directory.

It may be noted that the file that we want to read or write, may be present in some
other directory or folder. In that case, we can give absolute or relatative path of that
file along with its name, shown in the example below. The path separated by \ must
be proceeded by one more \ (backslash) to turn-off special feature of this character.
If the file to be read or written is in the same folder, in which python program is
present, we need not give its path.

Creating a file
For creation of new file, the file can be opened in ‘w’ mode. If the file already exists,
the contents can be overwritten. Also, if we want to be sure that no existing file gets
overwritten, then ‘x’ mode can be used to create new file. If the file already exists, it
will show error message. Given below is the example to open a file and write
contents to it.

Program to create file and add contents to it

Reading, writing, appending with with statement


The methods of dealing with files used in the above section may not be safe
sometimes. It may happen that an exception occurs as a result of operations on file
and the code exits without closing the file. To make it more convenient python
introduced another statement called with statement which ensures that file is closed
when the code within with is exited. Call to close() function is not required explicitly.
The syntax of how to use with statement for reading, writing and appending file is
given below.

Deleting a file or folder


A file can be deleted using remove() function from os module. Before using this
function you should move to the directory in which the file to be removed exists.
Similarly, to delete a folder or directory, os.rmdir() function can be used. The
directory to be removed must be empty or otherwise error will be shown. In the
example given below, we want to delete a file name “delete_123.py”. os.listdir()
function is used to display the list of files present in a directory.

You might also like