Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
4 views25 pages

Python 2

Uploaded by

neuvillette0070
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)
4 views25 pages

Python 2

Uploaded by

neuvillette0070
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/ 25

1.

40
on (BBA (CA)- Sem. V]

Program 1.27: Write a pvthon program to count repeated character in Introdute


a
Sample string:
import collections
'theauickbrownfoxjumpsoverthelazydog
string.
str1 = thequickbrownfoxj umpsoverthelazydog'

d = collections. defaultdict (int)


for c in str1:
d[c]
Tor c in sorted(d, key.d.get, reverse. True):
if d[c] > 1:
print('%s %d' % (C, d[c]))
Output:
2e
O 4

e 3
u 2
h 2
r 2

t 2

1.7 LISTS-INTRODUCTION, ACCESSINGLIS, OPERATO


WORKING NITH LISTS, FUNCTION &METHODS
A Python list is a mutable sequence of data values called
items or
can be of any type. List is one of the most frequently used and very elements. An
used in Python. versatile dat
Creating Elements ina List:
In Python programming, a list is created by placing all the items
square bracket [], separated by commas. (elements) ins
It can have any number of items and they may be of
string etc.).
different types (intege,
SyntaK: <list_name>=[value1, value2, value3,...,valuen]
Empty List:
listi = )
The empty Python list is written as twO square brackets
containing nothin
Examples of different lists:
be
list1 = ['C', java' 2016, 2018] # the items list need
not

the same type.


in a

list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]
Python [BBA (CA) Sem. V) 1.41 Introduction to Python

Example:
list1 = "apple", "banana", "cherry")
print(listl)
Output:
["apple", "banana" "cherry")

1.7.1 Accessing List


There are various ways in which we can access the elements of a list.
List Index:
We can use the index operator[ ]to access an item in a list. Index starts from 0. So, a
list having 5elements will have index from 0 to 4.
Trying to access an element other that this will raise an IndexError. The index must be
an integer. We can't use float or other types, this will result into TypeError.
Negative Indexing:
Python allows negative indexing for its sequences. The index of -1 refers to the last
item, -2 to the second last item and so on.
Slicing List:
We can access a range of items in a list by using the slicing operator: (colon).
Slicing can be best visualized by considering the index to be between the elements. So
if we want to access a range, we need two index that will slice that portion from the
list.
Basic Syntax toAccess Python List is:
<list_name> (index]
Examples:
listi=(1, 2, 3,4]
list2=('a', 'b', 'c']
print (1isti[0])
// till 2 means 2 won't be printed)
print(listi[e:2])
print(list2[-3:-1])
print (1isti[0:])
print (1ist2[ :2])
Output:

[1, 2]
['a', 'b']
[1, 2, 3, 4)
('a', 'b'
Python [BBA (CA)- Sem. V] 1.42 Introductlon to Pyth.
1.7.2 List Operation
Lists respond to the +and * operators much like strings; they mean concatenation an
Tepetition here too, except that the result is a new list, not a string.
In fact, lists
respond to all of the general sequence operations we used on strings
the previous section.
Python Expression Results Description
len([4, 5, 6, 7]) Length
(1,2,3] +[4,5,6] [1,2,3,4, 5,6] Concatenation
('Hi!)"3 ['Hi!, Hi!,'Hi!] Repetition
3 in [1, 2, 3] True Membership
for i in (1, 2,3): print i, 123 Iteration

|1.7.3 Working with Lists


1.7.3.1 Updating List
The single or multiple elements of lists can be updated by giving the slice on the let
hand side of the assignment operator. i.e. We can use assignment operator (-)t
change an item or a range of items.
We can add one item to a list using append0 method or add several items usin
extend) method.
We can also use + operator to combine two lists. This is also called concatenation.
The operator repeats a list for the given number of times.
Example:
list1 = ['C', 'java', 2016, 2018];
print("Value available at index 2: ")
print (listi(2] )
list1(2]= 2090 // Rerlacerment
print (list1)
Output:
Value available at-índex 2:
2016

['C,java', 2000, 2018]


Example:
list2 = ("apple", "banana", "cherry"];
list2.append(" orange"); /fddition of on elenf
print (1ist2)
Output:
["apple", "banana" "cherry", "orange"]
ython [BBA (CA) -Sem. V) 1.43 Introduction to Python

1.7.3.2 Delete List


We can delete one or more items from a list using the keyword del. It can
the list entirely. We can use del statement( if you know exactly even delete
are deleting). which elements you
We can use remove() method to remove the given item or
/tem at the given index. The remove) method is used to delete pop) method to remove an
if we do not know which element we the elements from a list
are deleting.
The pop() method removes and returns the last item if index is
helps us implement listsas stacks (first in, last out data not provided. This
Wecan also use the clear) method to structure).
empty a list.
Example:
list1 = ['C', "java', 2016, 2018];
print list1
del list1(2];
print "After deleting:", list1
list1.remove(java' );
print list1
Output:
['C', java', 2016, 2018]
After deleting: ['C', 'java', 2018]
['C', 2018]
1.7.4 Functions and Methods
Python includes the following list
functions:
all(): Return True if all elements of
the list are true (or if the list is
any): Return True if any element empty).
False. of the list is true. If the list is empty, return
enumerate(): Return an enumerate object. It
the items of list as a
tuple. contains the index and value of all
len): Return the length (the number
7 list): Convert an iterable of items) in the list.
(tuple,string, set, dictionary) to a
max): Return the largest item in list.
the list.
min): Return the smallest item in
the list.
sorted(): Return a new sorted list
(does not sort the list itself).
sum): Return the sum of all
Python includes elements in the list.
following list methods:
list.append(obj): Appends object obj to list.
list.count(obj): Returns count of how many
times obj occurs in list.
Python (BBA (CA)- Sem. V] 1.44
Introduction to P
list.
list.extend(seq): Appends the contents of seq to.
ust.index(obj): Returns the lowest index in list that obj appears.
ust.insert(index, obi): Inserts obiect obi into list at offset index.
spop(obj=list[-1): Removes and returns last object or obj
from list.
list.remove(obj): Removes object obj from ist.
list.reverse): Reverses objects of list in place.
ust.sort(func]): Sorts objects of list, use compare func if given.
Clear(): Removes all items from the list.
copy(): Returns a shallow copy of the list.
Program 1.28: For list methods.
lst = [123, 'xyz', 'pgr', 'abc', 'xyz ];
lst.reverse() ;
print("List: ", lst)
print("Count for 123:", lst.count(123))
print("Count for xyz: ", lst.count('xyz' ))
lst.remove('xyz')
print("List: ", lst)
lst.remove('abc')
print(" List: ", lst) ist
lst.pop () / Removes Jast element fom the
print (1st)
Output:
List: ['xyz', ' abc', 'pqr', 'xyz', 123]
Count for 123: 1
Count for xyz: 2
List: ['abc', pqr', 'xyz', 123]
List: ['pqr', 'xyz', 123]
('pqr' 'xyz']

1.8
TUPLE-INTRODUCTION, ACCESSING TUPLES, OPERATIONS
WORKING,FUNCTION AND METHODS, EXAMPLES
A tuple is a collection which is ordered and unchangeable. In Python tuples are
written with round brackets. This Python Data Structure is like a list in Python, is
heterogeneous container for objects.
The differences between tuples and lists are, we cannot change the elements of
tunle once it is assigned whereas 1n a list, elements can be changed. This means tha
Twhile vOu can reassign or delete an enture tuple, you cannot do the same to a sing
item or a slice. Tuples use parentneses,Whereas lists use square brackets
ython (BBA (CA) - Sem.V] 1.45
Introduction to Python
Advantages of Tuple:
1. Processing of Tuples are faster than Lists.
2. It makes the data safe because tuples are immutable
and hence cannot be
changed.
3. Generally tuples are used for heterogeneous (different) datatypes
and list for
homogeneous (similar) datatypes.
4. Tuples are used for String formatting.
Difference between Tuples and Lists:
1. The syntax of tuples is shown by parenthesis) whereas the syntax of lists
is shown
by square brackets[ ).
2. List has variable length, tuple has fixed length.
3. List has mustable nature, tuple has immutable nature.
4. List has more functionality than the tuple.
5. Typles are heterogeneous while lists are homogeneous. One has to
deal
individually with the items.
6. Tuples show structure whereas lists show order.
reating Tuple:
Atuple is created by placing all the items (elements) inside a
by comma. The parentheses are optional but is a good practice parentheses ), separated
to
have any number of items and they may be of different types write it. A tuple can
string etc.). (integer, float, list,
For example:
tup1 = ("apple", "orange", 2018) ; tup2 = (1, 2, 3, 4, 5);
tup3 = "a", "b", "c", "d";
The empty tuple is written as two parentheses containing nothing.
tup1 = (0;
To write a tuple containing a single value you
have to include a comma, even
though there is only onevalue:*
tup1 = (50,);
Like string indices, tuple indices start at 0, and they
SO on.
can be sliced, concatenated, and

Ogram 1.29: Python program for creating Tuples.


# empty tuple
my_tuple = ()
print (my_tuple)
# tuple having integers
my_tuple = (1, 2, 3)
print (my_tuple)
Python (BBA (CA)- Sem. V] 1.46 Introduction to P
# tuple with mixed
datatypes
my_tuple = (1, "Hello", 3.4)
print (my_tuple)
# nested tuple
my_tuple = ("Hello", [8, 4, 6], (1, 2, 3))
print (my_tuple)
* Tuple can be created without parentheses also called tuple packing
my_tuple = 3, 4.6, "tybca"
print (my_tuple)
# tuple unpacking is also possible
a, b, c = my_tuple
print(a)
print(b)
print(c)
Output:

(1, 2, 3)
(1, 'Hello', 3.4)
('Hello', [8, 4, 6], (1, 2, 3))
(3, 4.6, 'tybca' )
3
4.6

tybca

1.8.1 Accessing Tuples


To access values in tuple, use the square brackets for slicing along with the
index
indices to obtain value available at that index.
For example:
tup1 =("apple", "orange", 2018);
tup2 = (1, 2, 3, 4, 5, 6, 7 )
print "tup1[0]: ", tup1[0]
print "tup2 (1:6]:", tup2 (1:6)
When the above code is executed, it produces the following result:
tup1[0]: apple
tup2[1:6]: (2, 3, 4, 5, 6)
Python (BBA (CA) - Sem, V) 1.47 Introductlon to Python
Python Tuple Packing
Python Tuple packing is the term for packing a sequence of values into a tuple
without using parentheses.
myt uple=1,2,3 #0r it could have been mytuple=1, 2,3
>>> mytuple
Python Tuple Unpacking
The opposite of tuple packing, unpacking allots the values from a tuple into a
sequence of variables.
>>> a, b,c = mytuple
>>» print (a, b, c)
12 3
1.8.2 Tuple Operations eplai y 2)
Tuples respond to the + and * operators much like strings; they mean concatenation
and repetition here too, except that the result is a new tuple, not a string. The various
operations that we can perform on tuples are very similar to lists.
1 Concatenation:
Using the addition operator +, with two or more tuples, adds up all the elements into a
new tuple.
Example: (1, 2, 3) + (4, 5, 6)
Output: (1, 2, 3,4, 5, 6)
2. Repetition:
Multiplying a tuple by any integer, x willsimply create another tuple with all the
elements from the first tuple being repeated x number of times. For example, t*3
means, elements of tuple t will be repeated 3 times.
Example: ("Hi!',) * 4
Output: ('Hi!', 'Hi!', 'Hi!', 'Hi!')
3. Tuple Membership Test using in keyword:
In keyword, can not only be used with tuples, but also with strings and lists too. It is
used to check, if any element is present in the sequence or not. It returns True if the
element is found, otherwise False.
Example:
#in operation
tup = ('a', 'p','p', 'l','e',)
print('a' in tup) # Output: True
print('b' in tup) # Output: False
# Not in operation
print('g' not in tup) # Output: True
Python [BBA (CA) - Sem. V] 1,48 Introduction to Pytho
4. Iterating Through a Tuple:
Using a for loop we can iterate though each item in a tuple.
Example:
for name in ('mom','dad'):
print("Hello" , name)
Output:
# Hello mom
# Hello dad

Python Expression Results Description Length


(1, 2,3) + (4,5, 6) (1, 2,3, 4, 5, 6) Concatenation
(Hi!')*4 ('Hi!', Hi!, 'Hi!', Hi!) Repetition
3in (1, 2, 3) True Membership
for x in (1, 2, 3): print x, 123 Iteration

1.8.3 Working of Tuple


Y1.8.3.1 Updating Tuple
Tuples are immutable which means you cannot update or change the values of tuple
elements. You are able to take portions of existing tuples to create new
following example demonstrates: tuples as the
tup1 = (10, 32.76)
tup2 = ('abc' . xyz')
# tup1[0] = 100 is not valid
# So create a new tuple as follws:
tup3 = tup1 + tup2
print tup3
When the above code is executed, it produces the following
result:
(10, 32.76, 'abc', " xyz')
We can use + operator to combine two tuples.
This is also
called concatenation.,
We can also repeat the elements in a tuple
for a given number of times using the
operator.
>>> (1,) * 5
(1, 1, 1, 1, 1)
Both + and operations result into a new tuple.
1.8.3.2 Deleting Tuples
Deleting Tuple:
Removing individual tuple elenmentS 15 n0t Possible. There is, of course nothing
reong with putting together another tuple with the undesired elements
discarded.
Python [BBA (CA) - Sem. V] 1.49
Introduction to Python
To explicitly remove an entire tuple, just use the del statement.
Example:
tup = ("apple" "orange", 2018);
print tup
del tup
print "After deleting tup:
print tup
Output:
('apple', 'orange 2018);
After deleting tup:
Traceback (most recent call last):
File "test.py", line 5, in <module>
print tup;
NameError: name 'tup' is not defined
This produces an exception, this is because after del tup tuple does not exist any
more.

Deleting elements of tuple:


One way to delete the elements from the tuple , we have to convert into list and then
perform deletion.
Program 1.30: Write Python program for deleting elements from Tuple.
# Python program to remove an item from a tuple.
#create a tuple
tup = "a", "b", "c", "d", "e", "f", "g", "h", 10
print (tup)
#tuples are immutable, so you can not remove elements
#using merge of tuples with the + operator you can remove an item and it
will create a new tuple
tup = tup[:2] + tup[3:]
print (tup)
#converting the tuple to list
lst =list (tup)
#use different ways to remove an item of the list
lst.remove("h")
#Converting the tuple to list
tup = tuple(1st)
print(tup)
Output:
('a', 'b', 'c', 'd', 'e', 'f', 's', 'h', 10)
('a', 'b', 'd', 'e', 'f', 'g', 'h', 10)
('a', 'b', 'd', 'e 'f', 'g', 10)
Python [BBA (CA) - Sem.
V] 1.30 Introducton to Pyth
1.8,4 Function and Methods
Functions:
Python includes the following tuple functions:
1. cmp(tuple1, tuple2):
Compares elements of both tuples.
This is used to Compare two tuples. It will return either 1, 0
or 1,
upon whether the two tuples being compared are similar or not.
depending
The cmp) function takes two tuples as arguments, where both of them are
compared. If T1 is the first tuple and T2 is the second tuple, then:
if T1> T2, then cmp(T1, T2) returns 1
if T1 = T2, then cmp(T1, T2) returns 0
if T1>T2, then cmp(T1, T2) returns -1
2. len(tuple):
This function is used to get the number of elements inside any tuple.
Example: len( (1, 2, 3)) output: 3
3. max(tuple): Returns item from the tuple with max value.
4. min(tuple): Returns item from the tuple with min value.
5. tuple(seq): This method converts a list of items into tuples.
Program 1.31: Python program for built in Tuple function.
aList = ('xyz', "pqr', 'abc');
aTuple = tuple (aList)
print("Tuple elements: " aTuple)
# use of max() method:
print("Max value element: ", max (aTuple) )
# use of min() method:
print ("Ma value element: ", min(aTuple))
# use of len() method:
tuple1, tuple2 = ('xyz , pqr','spq' ), (450, 'abc')
print ("First tuple length: ", len(tuple1) )
print ("Second tuple length: " len(tuple2))
Output:
Tuple el ements: ('xyz', 'pqr', 'abc')
Max value element: xyz
Max value element: abc
First tuple length: 3
Second tuple length: 2
Python [BBA (CA) - Sem. V] 1.51 Introduction to Python

Methods:
Python Tuple Methods:
JA method is asequence ofinstructions toperform on something. Unlike afunction, it
does modify the construct on which it is called. You call a method using the dot
operator in python. Python has two built-in methods that you can use on tuples.
1. index(x): Return index of first item that is equal to x.
Example:
>>> a=(1, 2,3,2,4,5,2)
>>> a.index(2)
Output: 1
As you can see,we have 2s at indices 1,3, and 6. But it returns only thefirst index.
2. Count(x): Return the number of items is equal to x.
Example:
>>> a=(1,2,3,2,4,5,2)
>>> a.cOunt (2)
Output: 3
Program 1.32: Write a Python program to create a list of tuples with the first element as
the number and second element as the square of the number.
1_range=int (input ("Enter the lower range:"))
u_range=int(input(" Enter the upper range:"))
a=[(x,x**2) for x in range(1_range, u_range+1)]
print (a )
Output:
Enter the lower range:1
Enter the upper range:4
((1, 1), (2, 4), (3, 9), (4, 16)]
Examples:
Program 1.33: Write a Python program to add an item in a tuple.
#create a tuple
tuplex =(4, 6, 2, 8, 3, 1)
print(tuplex)
#tuples are immutable, so you can not add new elements
#using merge of tuples with the + operator you can add an element and it
will create a new tuple
tuplex = tuplex + (9,)
print(tuplex)
#adding items in a specific index
Python (BRA (CA) Sem. V) 1.52
totroductlon to Py
Tuplex - tuplex[ :S] + (15, 20, 25) + tuplex[ :5]
print(t uplex)
#converting the tuple to list
listx list(tuplex)
SUse different ways to add items in list
listx.append(30)
tuplex tuple(listx)
print(tuplex)
Output:
(4, 6, 2, 8, 3, 1)
(4, 6, 2, S, 3, 1, 9)
(4, 6, 2, 8, 3, 15, 20, 25, 4,
6, 2, 8, 3)
(4, 6, 2, 8, 3, 15, 20, 25, 4,
6, 2, 8, 3, 30)
Program 1.34: Write a Python program to convert
a tuple to a string.
tup = ('e', 'x', 'e
'r','c', 'i', 's', 'e', 's')
str ="join(tup)
print(str)
Output:
exercises
Program 1.35: Write a Python program to get the 4"
from last of a tuple. element from front and 4" elemen!
#Get an item of the tuple
tuplex = ("p", "y", "t", "h", "o", "n", "b", "o"", "o", "k")
print (tuplex)
#Get item (4 element )of the tuple
by index
item = tuplex[3)
print(item)
#Get item (4" element from last)by
index negative
item1 = tuplex[ -4]

print(item1 )
Output:
(Cp', 'y', 't', h', 'o' 'n', "b', 'o', 'o', 'k'
h
Python [BBA (CA) - Sem. V) 1,53 Introduction to Python

Program 1.36: Write a Python program tofind the repeated items of a tuple.
#Create a tuple
tuplex = 2, 4, 5, 6, 2, 3, 4, 4, 7
print (tuplex)
#return the number of times it appears in the tuple.
count = tuplex.count (4)
print (count)
Output:
(2, 4, 5, 6, 2, 3, 4, 4, 7)

Program 1.37: Write a Python program to check whether an element exists within a tuple.
tuplex = ("w", 3, "r", "e", "s", "o", "u", "r", "c", "e")
print ("r" in tuplex)
print (5 in tuplex)
Output:
True
False
NmYYYNYNYYYTrYYYY YYYYTA
DICTIONARIES-INTRODUCTION, ACCESSING VALUES IN
1.9 DICTIONARIES, WORKING WITH DICTIONARIES, PROPERTIES,
FUNCTION, EXAMPLES
A dictionary is a collection which is unordered, changeable and indexed. In Python
dictionaries are written with curly brackets, and they have keys and values.
Dictionaries are optimized to retrieve values when the key is known.
Dictionaries are Python's implementation of a data structure that is more generally
known as an associative array. Adictionary consists of a collection of key-value
Each key-value pair maps the key to its associated value. pairs.
Creation of Dictionary:
Creating a dictionary is as simple as placing items inside curly braces (}
comma. An item has a key and the corresponding value separated by
value. expressed as a pair, key:
Each key is separated from its value by a colon (:), the
items are separated by commas,
and the whole thing is enclosed in curly braces. An
items is written with just twO curly braces, like this: {}. empty dictionary without any
Keys are unique within a dictionary while values may not
be. The values of a
dictionary can be of any type, but the keys must be of an immutable data type such as
strings, numbers, or tuples.
Python [BBA (CA) - Sem. V]
1.54
Introductlon to Pythe
Syntax:
dictionary_name ={
<key>: <value>,
<key>: <value>,

<key>: <value>
}
Or

dictionary_name =dict([
(<key>, <value>),
(<key>, <value),

(<key>, <value>)
J)
Where dict is built-in
function.
Example:
# empty dictionary with name dict
dict = {}

# dictionary with integer keys


dict = {1: 'apple', 2:
'orange'}
# dictionary with
mixed keys
dict = {'name':
abc', 1: [2, 4, 3]}
# using dict()
dict = dict({1:'apple', 2:'orange' )

# from sequence having each item


as pair a
dict = dict([(1, 'apple'), (2,
'orange')1)
1.9.1 Accessing Values in Dictionary
To access dictionary elements, square brackets
its value. are used along
with the key to obtain
Python [BBA (CA) Sem. V] 1.55 Introduction to Pyt

To access dictionary elements we need to pass key, associated to the value.


Syntax:
<dictionary_name> (key]
Example:
dict = ('Name ' "abc', 'Age': 20, 'Class': 'tybca')
print "dict['Name']: ", dict{ 'Name']
print "dict['Age']: ", dict['Age']
Output:
dict[ 'Name']: abc
dict['Age']: 20
If we attempt to access a data item with a key, which is not part of the dictionary, we
get an error.
dict = {'Name': "abc', 'Age': 20, 'Class': 'tybca'}
print "dict[ 'xyz']: ", dict['xyz']
Output:
dict['xyz']:
Traceback (most recent call last):
File "test. py", line 2, in <module>
print "dict['xyz']: ", dict[ 'xyz'];
KeyError: 'xyz'
1.9.2 Working with Dictionaries
1.9.2.1 Updating Dictionary
Adictionary can be updated by adding a new entry or a key-value pair, modifying an
existing entry,or deleting an existing entry as shown below:
Program 1.38:
dict = {'Name':'abc', 'Age': 20, 'Class': .'tybca')
dict['Age'] = 22 ; # update existing entry
dict['College'] = "College"; # Add new entry

print ("dict['Age']: ", dict['Age'])


print("dict[ 'College']:", dict[ ' College'])
Dutput:
dict[ 'Age']: 22
dict['College']: college
Python [BBA (CA) - Sem. V] 1.56
Introduction
Example: Python program for updating Dictionary.
dict1 = {'name' 'Omkar' ,'age': 20}
# update value

dicti['age'] =25
#Output: {'age': 25, 'name': '0mkar"}
print (dict1)
# add item

dict1['address' ] 'pune'
# Output: {'address':'pune, 'age': 25, 'name': Omkar'}
print(dict1)
Program 1.39: Print all key names in the dictionary, one by
one.
dict1 {'name':'Omkar', 'address': 'pune',
for x in dict1: print (x)
'phone':9897965867}
Output:
phone
name

address

Program 1.40: Program to print all values of dictionary.


dict1 = {'name':'Omkar' 'address': 'pune', 'phone':9897965867}
for x in dicti.values (0:
print (x)
Output:
Omkar
9897965867
pune

Programn 1.41: Program to print all keyS and values of dictionary.


dicti = {'name':'Omkar! 'address': 'pune', 'phone':9897965867}
for x, y in dict1.items ():
print (x, y)
Output:
address pune
phone 9897965867

name Omkar
ython [BBA (CA) - Sem. V] 1.57 Introduction to Python

1.9.2.2 Delete Dictionary Elements


A
dictionary element can be removed one at a time or can clear the entire contents of
a dictionary.To explicitly remove an entire dictionary, the del statement is used. The
del keyword removes the item with the specified key name:
1. Example using del:
dict1 = {'Name': 'abc', 'Age': 20, 'Class': 'tybca'}
del dicti( 'Name']; # remove entry with key 'Name
dict1.clear(); # remove all entries in dict
del dict1 ; # delete entire dictionary
print "dict1[ 'Age']: ", dicti['Age']
Thisproduces the following result. Note that an exception is raised because after del
dict dictionary does not exist any more.
dict['Age']:
Traceback (most recent call last):
File "test. py", line 5, in <module>
print "dict['Age']: ", dict[ 'Age'];
TypeError: 'type' object is unsubscriptable
2. The clear) method empties the dictionary:
Example using clear):
dicti = {'name':"Omkar', 'address': 'pune', 'phone':9897965867}
dict1.clear()
print(dict1)
# Output: )
The pop() method removes the item with the specified key name:
Example using pop):
dict1 = {'name':'Omkar', 'address':'pune', 'phone':9897965867}
dict1.pop('address')
print (dict1)
# Output: {'name':'Omkar', "phone':9897965867}
The popitem) method removes the last inserted item.
Example using popitem):
dict1 = {'name':'Omkar' 'address' 'pune', 'phone':9897965867)
dicti.popitem( )
print (dict1)
# Output: {'name 'Omkar', 'address': 'pune'}
Python (8BA (CA) Sem. V] 1.59 Introduction to Pthon

Example:
>>» d= {0: 'a', 1: 'a', 2: 'a', 3: 'a'}
>>> d

{0: 'a', 1: 'a', 2: 'a', 3: 'a'}


»» d[o) = d[1] = d[2)
True

More than one entry per key not allowed. Which means no duplicate key is allowed.
When duplicate keys encountered during assignment, the last assignment wins,
means the second occurrence will override the first.
Example:
dict = {'Name' : 'Omkar', 'Age ': 20, ' Name': 'Mani'}
print "dict[ 'Name ']: ", dict[ "Name']
Output:
dict['Name']: Mani
Keys must be immutable. Which means you can use strings, numbers or tuples as
dictionary keys but something like ['key] is not allowed. <
Example:
dict = (['Name'): 'Omkar', 'Age': 20}
print "dict[ 'Name']: ", dict[ 'Name']
# Output: error

Program having atuple as adictionary key, because tuples are immutable:


>»> d= {(1, 1): 'a', (1, 2): 'b', (2, 1): 'c', (2, 2):'d'}
>>> d[(1, 1) ]
'a

»» d[(2, 1)]
'c'
1.9,4 Function and Methods
Python includes the following dictionary functions:
1. cmp(dicti, dict2): Compares elements of both dict.
2. len(dict): Gives the total length of the dictionary. This would
number of items in the dictionary. be equal to the
3. str(dict): Produces a printable string representation of a
4. type(variable): Returns the type of the passed
dictionary.
dictionary, then it would return a dictionary type. variable. If passed variable is
Example:
dict = {'Name' : 'abc', 'Age': 20);
#usage of len( ) method
print "Length: %d" %len (dict) #0utput:
Length: 2
# usage of type() method
Python [BBA (CA) - Sem. V] 1.60
Introduction to
print "variable Type: %s" %type(dict)
FOutput:Variable Type: <type 'dict'>
#usage of str() method.
print "Equivalent String: %s" %str (dict)
F0utput: Equivalent String: {'Age': 20, 'Name': abc'}
Python includes following dictionary
methods:
. dict.clear): Removes all elements of dictionary dict.
2. dict.copy): Returns a shallow copy of
3. dictionary dict.
dict.fromkeys(): Create a new dictionary with keys from seq and
value. values se
4. dict.get (key, default=None): For key key, returns value
dictionary. or default if kev
5. dict.has_key (key): Returns true if
6. dict.items(0: Returns a list of key in dictionary dict, false otherwise.
7. dict.keys(): Returns list dict's (key, value) tuple pairs.
of dictionary dict's keys.
8. dict.setdefault(key,
if key is not already indefault=None): Similar to get), but will set dict{key]=dei:
9. dict.update(dict2): Adds dict.
10. dict.values (): dictionary dict2's key-values
Returns list of dictionary dict's pairs to dict.
Program 1.43: To show usage of all values.
dict = {'Name': methods of dictionary.
# usage of items 'abc', 'Age': 20}
() method.
print("Value: %s" % dict.items())
# usage of
update() method.
dict = {'Name' :
dict1 = {'Sex': 'abc', 'Age': 20}
'female' }
dict.update(dict1)
print("Value: %s" % dict)
# usage of
keys() method.
print("Value: %s" % dict.keys()
# usage of
values() method.
print("Value: %s" % dict.values
())
# usage of
copy() method.
dict2 = dict.copy()
print("New Dictionary : %s" %
# clear() method. str(dict2))
print("Start Len: 3d" %len(dict))
dict.clear()
print("End Len: %" %
len(dict))
Python [BBA (CA) - Sem. V) 1.61 Introduction to Python

Output:
Value: dict_items([('Name 'abc'), ('Age', 20)])
Value: {'Name': ' abc', 'Age': 20, Sex': 'female'}
value: dict _keys(['Name 'Age', 'Sex'])
value: dict_values(['abc' 20, 'female'])
New Dictionary: {'Name': 'abc', 'Age': 20, 'Sex': 'female '}
Start Len: 3
End Len: 0

Examples:
Program 1.44: Write a Python script to sort (ascending and descending) a dictionary by
value.
import operator
d = {1: 2, 3: 4, 4: 3, 2: 1, 0: e}
print('Original dictionary :',d)
sorted _d =dict (sorted(d. items (), key=operator. itemgetter (1)))
print('Dictionary in ascending order by value : ',sorted_d)
sorted _d = dict(sorted(d. items(), key=operator. itemgetter(1), reverse=True) )
print('Dictionary in descending order by value:',sorted_d)
Output:
Original dictionary : {1: 2, 3: 4, 4: 3, 2: 1, @: e}
Dictionary in ascending order by value: {0: 0, 2: 1, 1: 2, 4: 3, 3: 4}
Dictionary in descending order by value: (3: 4, 4: 3, 1: 2, 2: 1, 0: 0}
Program 1.45: Write a Python script to add a key to adictionary.
Sample Dictionary: {0: 10, 1: 20) Expected Result :{0: 10, 1: 20, 2: 30}.
d= (0:10, 1:20)
print (d)
d. update({2:30})
print (d)
Write aPython script to concatenate following dictionaries to create a new
one.

Sample Dictionary:
dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}
Expected Result: {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}
dic4 = }
for d in (dic1, dic2, dic3): dic4 . update (d)
print (dic4)
Python [BBA (CA) Sem. V] 1,62 1ntroduction to hn
Program 1.46: Write a Python script to check if agiven key already exists in: adictionan
d = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60)
def is_key_present (x) :
if x in d:
print('Key is present in the dictionary')
else:
print("Key is not present in the dictionary')
is_key_present (5)
is_key_present (9)
Output:
Key is present in the dictionary
Key is not present in the dictionary
Program 1.47: Write a Python program to iterate over dictionaries using for loops.
d= {'x': 10, 'y': 20, 'z': 30}
for dict_key, dict value in d.items():
print (dict_key, '->',dict_value)
Output:
y -> 20
Z -> 30
X -> 10

Program 1.48: Write a Python script to generate and print a dictionary that contains
number (between 1and n) in the form (x, x*x). Sample Dictionary (n =5) : Expected Out
:{1: 1, 2: 4, 3:9, 4: 16, 5: 25)
n=int(input("Input a number "))
d = dict()

for x in range(1, n+1):


d[x]=x*x
print (d)
Output:
10
(1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7:
49, 8: 64, 9: 81, 10: 100}
Program 1.49: Write a Python script to print a dictionary
between 1and 15 (both included) and the values are where the kevs are numbe
square of keys. d=dict)
for x in range (1,16):
d[x]=x**2
print (d)
Output:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9:
121, 12: 144, 13: 169, 14: 196, 15: 225) 81, 10: 100,
ython [BBA (CA) - Sem. V] 1.63 Introduction to Python

Program 1.50: Write a Python program to combine two dictionary adding values for
common keys.
d1 = {'a': 100, 'b': 200, 'c':300}
d2 = {"a': 300, 'b': 200, 'd':400}
Sample output: Counter ({'a': 400, 'b': 400, 'd': 400, 'c': 300})
from collections import Counter
d1 = {"a': 100, 'b': 200, 'c':300}
d2 = {'a': 300, 'b': 200, 'd':400}
d = Counter(d1) + Counter (d2)
print (d)

rogram 1.51: Write a Python program to create and display all combinations of
etters, selecting each letter from a different key in a dictionary. Sample data :
1a',b], 2:[C,d]} Expected Output:
ac

ad
bc

bd
import itertools
d ={'1':['a','b'], '2':['c','d']}
for combo in itertools. product(*[d[k] for k in sorted (d. keys() )]):
print("".join(combo) )
TOgram 1.52: Write a Python program to create a dictionary from two lists without
osing duplicate values.
Sample lists: ['Class-v', 'Class-VI', 'Class-VII', Class-VIIT'l, [1, 2, 2, 3]
Expected Output: defaultdict(<class 'set'>, {'Class-VII': (2), 'Class-VI':
{2}, 'C1ass -VIII': (3}, 'Class-V': {1}})
from collections import defaultdict
class_list = ['C1lass -V', 'Class-VI', 'Class -VII', 'Class-VIII']
id_list = [1, 2, 2, 3]
temp = defaultdict(set)
for c, i in zip(class_list, id_list):
temp[c].add(i)
print (temp)
hon [BBA (CA) Sem. V] 1,64
Introduction to
Program 1.53: Write a Python program to match key values in two dictionaries
dictionary: ('key1': 1, 'key2': 3, 'key3': 2), ('key1': 1, 'key2': 2} Expected output: Sat,
present in both x and y. keyl:;
X= {'key1': 1, 'key2': 3, 'key3': 2}
y = {'key1': 1, 'key2': 2}
for (key, value) in set(x.items ()) & set (y.items()):
Print( %s: %s is present in both x and y' % (key, value))

FUNCTIONS-DEFINING A FUNCTION, CALLING A FUNCTIO


1.10 TYPES OF FUNCTION, FUNCTION ARGUMENTS,
ANONYMOn
FUNCTION, GLOBAL AND LOCAL VARIABLE, EXAMPLES
A function is defined as a block of organized,
related action. reusable code used to perform a sine
To provide a high degree of modularity Functions are
There are two types of Functions: used.
(a) Built-in Functions: Functions that are predefined
We have used many predefined functions in Python.
and organized into a libr:
(b) User-Defined: Functions that are
created by the programmer to meet t
requirements.
Advantages of Functions:
1. Tomakes the code easier to manage, debug,
and scale, functions are used.
2. Every time you need to execute a sequence of
call the function, so that we can reuse the statements, all we need to do is
code.
3. Functions allow us to change
work on different functions.
functionalityeasily, and different programmers c
1.10.1 Defining a Function
Folowing are the rules to define a function in Python:
Function blocks begin with the keyword def followed by the
parentheses (). function name a
The input parameters or arguments should be placed within
The first statement of a function can be these parentheses.
an optional statement th
documentation string of the function or docstring or documentation string. It
used to explain in brief, what a function does.
The code block within every function starts with acolon () and is
The return statement is used to exit a function. Areturn
indented.
statement with 1
arguments is the same as return None.
Syntax:
def function _name( param1, param2,.. ):
""function docstring"""
function_body
return [expression)
Python [BBA (CA) - Sem. V] 1.65 Introduction to Python

By default, parameters have apositional behavior and you need to inform them in the
same order that they were defined. Every function must be defined before it iscalled.
How function works in Python:
def functionName():

functionName():

Fig. 1.23
Example:
# function without parameters
def my_function ():
print("Hello from a function")
# A string as input parameter and prints it on standard screen.
def fun( str ):
"This prints a passed string into this function"
print str
return

1.10.2 Calling a Function


Defining a function only gives it a name, specifies the parameters that are to be
included in the function and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it
from another function or directly from the Python prompt.
Tocall a function means that you are telling the program to execute the function. If
there is a return value defined, the function would return the value, else the function
would return None.
To call a function, use the function name followed by parenthesis, if you need to pass
parameters/arguments to the function, you write them inside the parentheses.
Syntax: function_name (arg1, arg2)
Example:
1. Calla function that performsa task and has no return value.
def my_function ():
print("Hello from a function")

my_function()
Output: 'Hello from a function

You might also like