[go: up one dir, main page]

0% found this document useful (0 votes)
7 views49 pages

Unit 3

Uploaded by

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

Unit 3

Uploaded by

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

Dictionaries, Tuples

and Functions
Unit-3
Dictionary
• A dictionary is a python data structure that is used to
store the data in the form of key-value pairs. It is a
collection.
• Defining a dictionary:
Dict_name= { <key1>:<value1>,
<key2>:<value2>,
.
.
}
• A dictionary can also be constructed using the
constructor function dict().
Dict_name= dict([(key,value),(key,value),
(key,value)])

Ex: d1={‘dell’:’core i5’,’Lenovo’:’core i7’,’hp’:’core i9’}


d1=dict ([(‘dell’,’core i5’),(’Lenovo’,’core i7’),(’hp’,’core
i9’)])
Dictionary properties
• They are mutable.
• They do not allow duplicates to be stored.
• The keys and values can be of any data type.
• The keys are always unique.
Accessing Dictionary Values

print(eng2sp['two'])
#dos
eng2sp[‘four’]=‘cuatro’
- If the key is not present in the dictionary, an exception
is raised.
• x=len(eng2sp) #gives the length of the dictionary
• ‘one’ in eng2sp
- The above statement returns True if ‘one’ appears as a
key in the dictionary.
- Similarly, not in operator works on the keys in the
dictionary.
- If you want to check the presence of a value in the
dictionary, we use values().
vals= list(eng2sp.values())
print(vals)
Looping and Dictionaries
• Dictionary is a collection type and hence can be used
as an iterable object in the for loop.
• When used in the for loop, it traverses the keys in the
dictionary.
Programs
• Write a program to find the sum and average of dictionary
values.
• In a class of 10 students, it is required to store the marks
scored along with their USNs. Use an appropriate data
structure to store the marks. Also, retrieve the students who
have scored marks above average.
• Given a list of names, create a dictionary with key as a
starting letter and value as all names starting with that letter.
• Merge the contents of 2 dictionaries.
• Sort the elements in the dictionary based on the keys.
• Add a key value pair at the beginning of the given dictionary.
Dictionaries as a set of counters
• Suppose we have a problem of finding the frequency
of each letter in the given string.
• Solutions:
1. Use 26 counter variables, one for each letter in the
alphabet.
2. Create a dictionary with 26 letters as keys, and the
corresponding values will be counters.
• The get() method
• Returns the value of the key specified.
dictionary.get(keyname, default_value)
- If key is not present in the dictionary, the
default_value is returned.

- Modify the letter frequency program using the get()


method.
Dictionaries and Files
• One common applications of dictionaries is to count
the occurrences of words in a given text file.
- Write a program to count the frequency of each word
appearing in the file.
Tuples
• Tuples are a sequence of values separated by commas.
• The values stored in the tuple can be of any type.
• They can be indexed by integers just like list.
• Tuples are immutable unlike lists.
• Defining tuples:
t=‘a’,’b’,’c’
or
t=(‘a’,’b’,’c’)
To create a tuple with a single
element, you have to include the final comma:

Without the comma Python treats (’a’) as an expression


with a string in parentheses that evaluates to a string:
Another way to construct a tuple is the built-in
function tuple.
● If the argument is a sequence
● With no argument,it creates (string, list, or tuple), the result of
an empty tuple: the call to tuple is a tuple with the
elements of the sequence:
Tuple
• A tuple is accessed in the same way as a list.
Comparing Tuples
Tuple Assignment
• Python allows tuple to be written on the left side of the
assignment operator.

- The assignment takes place


element by element from right
hand side to left hand side.
- Given an e-mail id, find the username and the domain name.
Dictionaries and Tuples
• We can create a list of key-value pairs, using the items()
function.
• In this list, each element is a tuple.
Sorting dictionary elements by Key.
- Consider the below example:
d={2:200,4:2399,1:3748}

- Hence, converting a dictionary to a list of tuples, is a way


to output the contents of a dictionary sorted by key.
Multiple Assignment with
Dictionaries
Sorting the Dictionary by values
Count the occurrences of words
• Given a text file, write a program to count the number of occurrences
of each word in it.
- We make use of string translate(), to remove any punctuation marks
in the text.
- Syntax:
string.translate(table)
- Here, the table is a mapping table, that contains the ‘from’ pattern
and the to ‘pattern’.
- To create this mapping table, we make use of the maketrans()
function.
D1= str.maketrans(x, y, z)
- If only one parameter is mentioned, it must be a dictionary
containing the mapping of values.
- If x and y mentioned, the x will be replaced with y.
- z is the value that needs to be deleted from the string.
- Returns a dictionary containing a mapping of key values. Each
key will be replaced with the corresponding value.
• Write a program to count the occurrence of each word in the
given text file. And sort the result based on the word length.
• Write a program to sort the list of words from longest to shortest.
• Write a Python program to add an item in a tuple.
• Write a Python program to convert a tuple to a string.
• Write a Python program to get the 4th element and 4th element from
last of a tuple.
• Write a Python program to find the repeated items of a tuple.
• Write a Python program to check whether an element exists within a
tuple.
• Write a Python program to convert a list to a tuple.
• Write a Python program to remove an item from a tuple.
• Write a Python program to find the index of an item of a tuple.
• Write a Python program to find the length of a tuple.
Convert tuple into a dictionary
Remove empty tuple from a list
of tuples
List Tuple
[] ()

List are mutable Tuples are immutable

Iterations are time-consuming Iterations are comparatively Faster

Inserting and deleting items is easier with a list. Accessing the elements is best accomplished with a tuple data
type.

Lists consume more memory Tuple consumes less than the list

Lists have several built-in methods. A tuple does not have many built-in methods because of
immutability

A unexpected change or error is more likely to occur in a list In a tuple, changes and errors don't usually occur because of
immutability.

If the content is not fixed keeps on changing,then it is better to If the content is fixed ,then it is better to opt list.
opt list Ex:name,usn,emp_id,latitude and longitude of a location
Ex: student marks,age,employee salary,weather,
List Tuple Dictionaries
A list is a non-homogeneous A Tuple is also a non- A dictionary is also a non-
data structure that stores the homogeneous data structure homogeneous data structure
elements in columns of a single that stores elements in columns that stores key-value pairs.
row or multiple rows. of a single row or multiple rows.

The list can be represented by Tuple can be represented by ( ) The dictionary can be
[] represented by { }

The list allows duplicate Tuple allows duplicate elements The dictionary doesn’t allow
elements duplicate keys.

Example: [1, 2, 3, 4, 5] Example: (1, 2, 3, 4, 5) Example: {1: “a”, 2: “b”, 3: “c”,


4: “d”, 5: “e”}

A list can be created using the Tuple can be created using the A dictionary can be created
list() function tuple() function. using the dict() function.

A list is mutable i.e we can A tuple is immutable i.e we can A dictionary is mutable, ut Keys
make any changes in the list. not make any changes in the are not duplicated.
tuple.

List is ordered Tuple is ordered Dictionary is ordered (Python


3.7 and above)
Functions
Definition
● A function is a named set of python statements that
perform a certain computation.
● A function name must be followed by a set of simple
parenthesis ().
● The expression/s written within () are called arguments.
● A function may or may not return a value, if yes, it is
called the return value.
● A function generally performs a specific task.
Function Elements

● A function has 2 elements:


○ A function definition
○ A function call
1. Function Calls:
- This is a statement which call the function by its name.
Syntax:
Variable= function_name( arguments)
- This statement is also called as method invocation.
Function Calls
● Ex:
s=‘Python’
length=len(s)
Print(length)
type(s)
Function Definition
● This is the set of statements that define the function.
● It begins with the keyword: def
● The def keyword is followed by the name of the function and
the set of statements.
Ex:
def print_name(name):
print(“Hi”,name)
Built-in Functions
● There are 2 types of functions:
● Built-in functions and user defined functions.
● Built-in functions are those whose definition is already
available
Ex: len(), min(), max() etc.
● There are a number of built-in functions available in python,
which can be directly called with the need to define them.
1. Type-conversion functions:
- They convert the data from one type to another.
- int(‘32’)- converts the string value ‘32’ to integer value 32.
- float(32)- converts the integer to a float.
2. Math functions: In order to use the math functions, we need to
import the library math.
Import math
- The above line needs to be included at the beginning of the
program.
- This statement creates a module object named math.
● The module object contains the functions and variables defined
in the module.
● To access one of the functions in this module, we need to
specify the name of the module followed by a dot notation.
● Ex:
math.sin(radians)
math.sqrt(5)
Adding new functions
● If we want to add our own functions, we need to provide a
function definition before using them, using the def keyword.
● Once, the function is defined, we can call it any number of
times in the program.
● Hence, functions increase re-usability.
Some examples
● Write a function to find the maximum of 3 numbers.
● Write a function to find the factorial of a given number.
● Write a function to check if the given number is a palindrome.
● Write a program to check if a given string is a palindrome.
● Write a function to check if the given number is perfect number.
● Write a function to add the contents of 2 lists.
● Write a function to join 2 lists.
● Write a function to multiply the list elements with a scalar.
● Write a Python program that accepts a hyphen-separated sequence of
words as input and prints the words in a hyphen-separated sequence
after sorting them alphabetically.
● Write a Python function to create and print a list where the values are
square of numbers between 1 and 30 (both included).
Passing lists and dictionaries to functions
- When lists and dictionaries need to be passed as arguments, we
need to mention the object names in the function call, just like
any other object.
- The difference here is, when lists and dictionaries are passed as
arguments, an alias is created to the original object in the main
function. For all other objects, a separate copy of the object is
passed.
- As a result, if the elements in the lists and dictionaries are
modified in the functions, it gets reflected in the main function
also.
Default arguments
● Python allows you to define default arguments in the functions.
● Suppose the arguments are not passed in the function call, the default
values will be considered.
Ex:
def func(x1=10,y1=20):
return(x1+y1)

x=100
y=200
res=func(x)
print(res)
The flow of execution
● The execution always begins from the first statement of the
program.
● The statements in the functions get executed only after it is
called.
● Hence, all functions need to be defined before they are called.
● If a function is called in the main function and it is defined after
the main function, python throws an error.
Parameters and Arguments
● The variables passed in the function call statements are known as
arguments.
● These arguments are assigned to new variables called as parameters.

Ex:
def message(msg):
print(“The message is:”,msg)

m=“Hello”
message(m)

- Here msg in the function is called as parameter and it is the copy of the
argument passed in the function call. Any changes made to the parameter
does not reflect in the arguments.
Fruitful functions and void functions
● Some functions return the results back to the calling function,
and some do not.
● The functions that yield result or return the result are called as
fruitful functions. This is done using the return statement.
● Others that do not return the result are void functions.
● This applies to both built-in functions and user defined
functions.
● We use fruitful functions when the returned result is used for
some calculation.
Why Functions?
● The advantages of using functions are:
1. Creating a new function gives you an opportunity to name a
group of statements, which makes the program easier to read,
understand and debug.
2. Functions increase reusability and hence, reduces the length of
the program by reducing repetitive code. Modifications or
updating also become easy.
3. Dividing a large program into functions actually reduces the
amount of effort required to debug the errors.
Scenario based questions:

1. An organization needs to store the details of its employees such as


employee-id, name, department, position and salary. Build a python program
that builds this database by reading the data from the user. Also it should
allow to user to do the following options:
1. Add a new employee
2. Search an employee and display the details
3. Delete an employee

2. In an internet banking application it is highly critical to authenticate the


right user. The first level of authentication is done using username and
password. An user is allowed to login only after he has registered. If the user
is not registered, he has to first register himself by giving a strong password.
A password is strong if it has minimum of 8 characters, atleast 1 digit, 1
uppercase and 1 special character. Write a program that simulates the login
functionality.
3. Create a Python program to generate and print the dictionary with keys in
alphabetical order starting with ‘a’ and values ranging from 10 to 80 in steps
of 5. Write a function to check whether the values 20 and 45 present in the
dictionary, then print the findings.

4. Write a function that accepts a string and counts the number of


uppercase and lower case letters in it.

5. Write a function to find all duplicate characters in a string.

6.. Write a function that removes all duplicate values in a dictionary.

7. Remove all duplicate words in a given line of text.

You might also like