Unit 3
Unit 3
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)])
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.
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.
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.
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: