0% found this document useful (0 votes)
53 views44 pages

Unit 4 - v2-1

The document provides information about tuples in Python. It defines a tuple as an immutable ordered collection of elements separated by commas. It discusses creating and accessing tuples, updating tuples, deleting tuples, tuple operations and functions like concatenation, repetition, membership, comparison, length, max, min, sum, all, any, sorted, and converting sequences to tuples. It also discusses nested tuples, tuple methods like count and index, variable argument tuples, and the zip function.

Uploaded by

MANSOOR REEMA
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)
53 views44 pages

Unit 4 - v2-1

The document provides information about tuples in Python. It defines a tuple as an immutable ordered collection of elements separated by commas. It discusses creating and accessing tuples, updating tuples, deleting tuples, tuple operations and functions like concatenation, repetition, membership, comparison, length, max, min, sum, all, any, sorted, and converting sequences to tuples. It also discusses nested tuples, tuple methods like count and index, variable argument tuples, and the zip function.

Uploaded by

MANSOOR REEMA
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/ 44

VELAMMAL ENGINEERING COLLEGE, CHENNAI – 66

(An Autonomous Institution, Affiliated to Anna University, Chennai)

UNIT IV
TUPLES, SETS and DICTIONARIES

TUPLES:
➢ Tuple is an immutable ordered collection of elements enclosed in round brackets and
separated by commas
➢ A tuple can have heterogeneous data items (i.e) a tuple can have string and list as data
items as well.

It is very similar to lists but differs in two things.


• First, a tuple is a sequence of immutable objects.
• Second, tuples use parentheses to define its elements whereas lists use square brackets.

Creating a Tuple:

Creating a tuple is very simple and almost similar to creating a list. For creating atuple,
generally you need to just put the different comma-separated values within a parentheses
as shown below.
Syntax:
Tuple_name = (val 1, val2,...)

where val (or values) can be an integer, a floating number, a character, or a string.

Examples:
1. R=( )
print( R )

Output: ( )

2. T1= ( 1, 2 )
print( T1 )

Output: 1 2

3. T2= ( 1, 2 ,”abc”, 3.4, 5.8, 10 )


print( T2 )
Output: 1, 2 ,”abc”, 3.4, 5.8, 10

4. K= ( “Kiran”, “Manoj”, “ Dinesh” )


print( T2 )

Output: Kiran Manoj Dinesh

5. T1= ( 1.5 , 2.6 , 5.7 )


print( T1 )

Output: 1.5 , 2.6 , 5.7

Accessing Values in a Tuple:

Index in a tuple starts at 0 and operations like slice, concatenate can be performed on a tuple.

For example, to access values in tuple, slice operation is used along with the index or indices
to obtain value stored at that index

N = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

print( N[3:6] ) ===➔4 5 6


print( N[:8] ) ===➔1 2 3 4 5 6 7 8
print( N[4:] ) ===➔5 6 7 8 9 10
print( N[:] ) ===➔1 2 3 4 5 6 7 8 9 10

Updating Tuple:

Since Tuple is immutable , we can only extract values from one tuple into another tuple

T1= ( 1.5 , 2.6 , 5.7 )


T2 = ( 10, 20, 30 )
T3 = T1 + T2
print( T3 )

Output:
1.5 , 2.6 , 5.7 , 10, 20, 30

Deleting Elements in Tuple:

Since tuple is immutable, when we try to delete the element from Tuple it will raise an error

Example 1
T = (1,2,3,4,5,6,7,8,9,10)
del T[1]
print (T)
Output:
Traceback (most recent call last):
File "<string>", line 2, in <module>
TypeError: 'tuple' object doesn't support item deletion

Deleting a tuple entirely, however, is possible using the keyword del.

Example 2

K=(1,2,3,4,5,6,7,8,9,10)
del K
print(K)

Output:
Traceback (most recent call last):
File "<string>", line 3, in <module>
NameError: name ‘K' is not defined

Tuple Operations and functions:

The various Tuple operation are

1. Concatenation operation
2. Repetition operation
3. Membership operation
4. Iteration
5. Comparison
6. Length – len() function
7. Maximum- max() function
8. Minimum – min() function
9. sum() function
10.all( ) function
11.any() function
12.sorted() function
13.Convert sequence into Tuple-tuple() function

1. Concatenation:

D= (1,2,3,4,5)
E =( 10,20,30,40,50)
F=D + E
print(F))
Y=(‘a’,’b’,’c’) + (1.2,3.7,8.3)
print(Y)

Output:
(1, 2, 3, 4, 5, 10, 20, 30, 40, 50)
('a', 'b', 'c', 1.2, 3.7, 8.3)

2. Repetition
Repeats the element in the Tuple

U = (1, 2, 3)
print(U*3)

Output:
123123123

3. Membership Operation

in : checks whether the value is present in Tuple


a’ in (‘a’,’e’,’i’,’o’,’u’)

True

not in : checks whether the value is not present in the Tuple


3 not in (1,2,3,4,5)

False

4. Iteration

T = (10,20,30,40,50)
for var in T:
print(T.index(var),var)

Output:
0 10
1 20
2 30
3 40
4 50

5. Comparison

tuple1 = (1,2,3)
tuple2 = (1,2,4)
print (tuple1 == tuple2)= False
print (tuple1 < tuple2) = True
print (tuple1 > tuple2) = False

6. len( ):

len() function is used to find the no of elements in the Tuple

H = (1,2,3,4,5)
print(len(H))

Output:
5

7. max():

Find the largest value in the Tuple

numbers = (10, 22, 53, 53, 8, 9, 11, 45, 90, 7, 26)


print(max(numbers))

Output:
90

8. min():

Finds the minimum value in the Tuple


numbers = (10, 22, 53, 53, 8, 9, 11, 45, 90, 7, 26)
print(min(numbers))

Output:
7

9. sum()

Finds the sum of the elements in the tuple

tup = (5,10,1,3)
sum(tup)

Output:
19

10. all() :
Returns True if all elements of the tuple are true
x=(1,2,3,4)
all(x)

Output:
True

11. any() :
Returns True if any of the elements of the tuple are true
x=(1,0,3,4)
any(x)

Output:
True
12. sorted ( ) : Returns a new sorted tuple

x=(34,5,17,9)
sorted(x)

Output:
(5, 9, 17, 34)

13. Converting sequence into Tuple - tuple()

g = (1, 2, 3, 4)
t="Hello“
h=tuple(g)
j=tuple(t)
print(h)
print(j)

Output :
(1, 2, 3, 4)
('H', 'e', 'l', 'l', 'o')

Tuple Assignment:

Tuple assignment is a very powerful feature in Python. It allows a tuple of variables on the
left side of the assignment operator to be assigned values from a tuple given on the right side
of the assignment operator.
Each value is assigned to its respective variable. In case, an expression is specified on the
right side of the assignment operator, first that expression is evaluated and then assignment is
done.
1.( a ,b, c ) = (1 ,2 , 3 )
print( a, b , c)

Output:1 2 3

2.D=( 10, 20, 30 )


( x, y, z ) = D
print(x ,y, z )
Output:10 20 30

3.( i, j, k ) = ( 2+3, 4/2, 2+6%2 )


print( i, j , k)
Output:
5 2 2

Tuples for Returning Multiple Values

def max_min( L ):
x=max(L)
y=min(L)
return(x,y)

S=( 1 ,2, 3, 4, 5, 6, 7, 8, 9, 10 )
i, j= max_min(S)
Print(Highest value:”,i)
Print(“Lowest Value:”,j)

Output:
Highest value: 10
Lowest Value: 1
Nested Tuples:

1.U = (( “Manoj”, ”IT”, 98.56) , (“Jack”,”CSE”,95.78), (“Bobby”,”AIDS”,92.18))


U[0][0] ===➔ Manoj
U[0][1] ===➔ IT
U[0][2] ===➔ 98.56
U[1][0] ===➔ Jack
U[1][1] ===➔ CSE
[01][2] ===➔ 95.7
U[2][0] ===➔ Bobby
U[2][1] ===➔ AIDS
U[2][2] ===➔ 92.18

2.F = ( “Hello”, [ 1, 2, 3, 4, 5] )
print(F[0]) = Hello
print(F[1]) = 12345
print(F[1][2]) = 3
print(F[0][0]) = H

Tuple Methods

1. count( ) :

Returns the number of times a specified value appears in the tuple.

Syntax :
tuple.count(value)

E = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = E.count(5)
print(x)

Output:
2

2.index( ):
The index() method finds the first occurrence of the specified value.
The index() method raises an exception if the value is not found.

Syntax :
tuple.index(value)

S = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = s.index(8)
print(x)

Output:
3

Variable-length Argument Tuples:

Example 1:

S = (9,3)
q , r = divmod(*S)
print(q, r)

Output:
3 0
Example 2:

S = (9,3)
q , r = divmod(S)
print(q, r)

Output:
Traceback (most recent call last):
File "./prog.py", line 2, in <module>
TypeError: divmod expected 2 arguments, got 1

The zip() Function:

The zip() is a built-in function that takes two or more sequences and "zips" them into a
list of tuples. The tuple thus, formed has one element from each sequence.

Syntax:
zip(iterator1, iterator2, iterator3 ...)

T = (1,2,3,4,5)
C=[‘a’,’b’,’c’,’d’,’e’]
print(list((zip(T,C)))

Output:
[(1,’a’),(2,’b’),(3,’c’),(4,’d’),(5,’e’)]

Advantages of Tuple over List


• Faster than lists
• Make the code safe
• Tuples can be used as dictionary keys, whereas lists cannot
Tuples Vs Lists

SETS:
Set is a datatype in python which is mutable and unordered collections of elements without
duplicates.

Sets are same as lists without duplicate elements.

Syntax:

set_variable={val1, val2,...}

Example:

s={1, 2.0,"abc"}

Coversion of various Datatypes into sets:

List1=[1,2,3,4,5,6,5,4,3,2,1]
print(set(List1))
Tup1=('a','b','c','d','b','e','a')
print(set(Tup1))
str="abcdefabcdefg"
print(set(str))
print(set("she sells sea shells".split()))
Output:
{1,2,3,4,5,6}
{'a','c','b','e','d'}
{'a','c','b','e','d','f','g'}
{'sells','she','sea','shells'}

Sets – Methods , Functions & Operations:

1. Comparision :
s==t and s!=t
s==t returns True if the two sets are equivalent and False otherwise.
s! =t returns True if both the sets are not equivalent and False otherwise.

Example:

s={'a', 'b','c'}
t={"abc"}
z=set(tuple('abc'))
print(s==t)
print(s!=z)

Output:
False
False

2. membership :
The membership operator "in" returns true if the given element is present in the set and
false if it is not present.
The membership operator "not in" returns true if the given element is not present in set s and
false if the given element is present.

Example:

s={1,2,3,4,5}
print(3 in s)
print(3 not in s)
Output:
True
False

3. len(): Returns the length of the set without duplicates.


Syntax: len(set object)

Example:

s={1,2,3,4,4,5}
print(len(s))

Output:
5

4. max() : Returns the maximum value in a set.

Syntax: max(set object)

Example:

s={1,2,3,4,5}
print(max(s))
t={'a', 'c', 'b'}
print(max(t))

Output:
5
C

5. min() :
Returns the minimum value in the set.

Syntax: min(set object)

Example:

s={0, 1,2,3}
print(min(s))
t={'a', 'b', 'c'}
print(min(t))

Output:
0
a

6. sum() :Returns the sum of all the elements in a set.

Syntax: sum(set object)


Example:

s={1,2,3,4,5}
print(sum(s))

Output:
15

7. all() : Returns True if all elements in the set are True and False otherwise.

Syntax: all(set object)

Example:

s={0, 1,2}
t={-1, 1,2.0}
print(all(s))
print(all(t))
Output:
False
True

8. any() :
Returns True if any of the elements in the set is True.
Returns False if the set is empty.

Syntax: any(set object)

Example:

s={ }
t={1, -2, 2.0}
print(any(s))
print(any(t))

Output:
False
True

9. sorted():
Returns a new sorted list from elements in the set.

Syntax: sorted(set object)

Example:
s={5,2,1,4,3}
t={'c', 'a', 'd', 'b'}
print(sorted(s))
print(sorted(t))

Output:
[1,2,3,4,5]
['a', 'b', 'c', 'd']

10.set ( ) : Creates a set object.The items in a set list are unordered, so it will appear in
random order.

Syntax: set( sequence)

Example :
x = set(("apple", "banana", "cherry"))
print(x)

Output:

{'banana', 'cherry', 'apple'}

Set Methods
1.update(): Adds the given elements to the set without duplicates.

Syntax: s.update(sequence)

Example:

s=set([1,2,3,4,5])
t=set([6,7,8])
s.update(t)
print(s)
Output:
{1,2,3,4,5,6,7,8}

2.add(): Adds only one element to the set without duplicates.

Syntax: s.add(value)

Example:
s=set([1,2,3,4,5])
s.add(6)
print(s)

Output:
{1,2,3,4,5,6}

3.remove(): Removes only one element from set s.It returns KeyError if the given element
is not present in set s.

Syntax: s.remove(Value)

Example:

s=set([1,2,3,4,5])
s.remove(4)
print(s)

Output:
{1,2,3,5}

4.discard():

Removes only one element from the set s.It does not return error if the given element is not
present in set.

Syntax: s.discard(Value)

Example:

s={1,2,3,4,5}
s.discard(3)
print(s)

Output:
{1,2,4,5}

5.pop() :
Removes and returns any random elements from set s. Key error is raised if set s is empty.

Syntax: s.pop()

Example:

s={1,2,3,4,5}
s.pop()
print(s)

Output:
{1,2,3,4,}

6.clear() :
Removes all elements from the set.

Syntax: s.clear()

Example:

s=set([1,2,3,4,5])
s.clear()
print(s)

Output:
set()

7.copy() :

Returns a copy of set s

Syntax: s.copy()

Example:

s={1,2,3}
t={4, 5,6}
print(s.copy())

Output:
{1,2,3}

8. issubset() or s<=t
Returns True if every element in set s is present in set t and False otherwise.

Syntax: s.issubset(t)

Example:

s={1,2,3,4,5}
t={1,2,3,4,5,6,7,8}
print(s<=t)
Output:
True

9. issuperset() or s>=t
Returns True if every element in t is present in s and False otherwise.
Syntax: s.issuperset(t)

Example:

s={1,2,3,4,5}
t={1,2,3,4,5,6,7,8,9,10}
print(s.superset(t))

Output:
False

10.union() or s|t: Returns a set s that has elements from both set s and t.

Syntax: s.union(t)

Example:

s={1,2,3}
t={1,2,3,4,5}
print(s|t)
Output:
{1,2,3,4,5}

11.intersection() or s&t :

Returns a new set that has elements which are common to both the sets s and t.
Syntax: s.intersection(t)

Example:

s={1,2,3,4}
t={3,4,5}
z=s&t
print(z)
Output:
{3, 4}

12.intersection_update():

Returns a set that has elements which are common to both the sets s and t

Syntax: s.intersection_update(t)

Example:
s={1,2,3,4}
t={3,4,5}
s.intersection_update(t)
print(s)

Output:
{3, 4}

13.difference() or s-t:
Returns a new set that has elements in set s but not in set t.
Syntax: s.difference(t) (or) s-t

Example:

s={1,2,3,5,10}
t={1,5,3,2,8}
z=s-t
print(z)

Output:
{10}

14.difference_update():

Removes all the elements of another set from this set.

Syntax: s.difference_update(t)

Example:

s={1,2,3,4,5,6,12}
t={1,2,3,4,5,6,7,8,9,10}
s.difference_update(t)
print(s)

Output:
{12}

15.symmetric_difference(t) or s^t:
Returns a new set with elements either in s or in t but not both.

Syntax: s.symmetric_difference(t) (or) s^t

Example:

s={1,2,3,4,5,10}
t={1,2,3,4,5,6,7,8,9,10}
z=s^t
print(z)

Output:
{6,7,8,9}

16.isdisjoint():

Returns True if two sets have null intersection.

Syntax: s.isdisjoint(t)

Example:

s={1,2,3}
t={4,5,6}
print(s.isdisjoint(t))

Output:
True

17.enumerate():
Returns an enumerate object which contains index as well as value of all the items of set
as a pair.

Syntax: enumerate(s)

Example 1:

s={'a','b','c','d'}
print(list(enumerate(s)))

Output:
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]

Example 2:

s={'a','b','c','d'}
for i in enumerate(s):
print(i)

Output:
(0, 'a')
(1, 'c')
(2, 'b')
(3, 'd')
Dictionaries:
• Dictionaries are unordered collection of data values. Data values are stored in key-
value pair.
• Dictionaries are Python’s built-in mapping type. They map keys, which can be any
immutable type, to values, which can be any type, just like the values of a list or tuple.
• Dictionaries cannot have duplicate keys.

Creating a Dictionary:

❖ One way to create a dictionary is to start with the empty dictionary and add key-
value pairs. The empty dictionary is denoted {}:

Syntax:

dictionary_name = {key_1: value_1, key_2: value_2, key_3: value_3, ….}

Example:

T= { }
R={ ‘Rollno’ : 1 ,’Name’ : ‘Hari’,”course’ : ‘B.Tech’}
print(T)
print(R)

Output:

{ }

{ ‘Rollno’ : 1 ,’Name’ : ‘Hari’,”course’ : ‘B.Tech’}

The first assignment creates an empty dictionary named T.


The other assignments add new key-value pairs to the dictionary.

The key-value pairs of the dictionary are separated by commas. Each pair contains a key
and a value separated by a colon.

The order of the pairs may not be what you expect. Python uses complex algorithms to
determine where the key-value pairs are stored in a dictionary.

❖ Another way to create a dictionary is to provide a list of key-value pairs using the
same syntax as the previous output:

It doesn’t matter what order we write the pairs. The values in a dictionary are accessed
with keys, not with indices, so there is no need to care about ordering.
Accesing values in dictionary:

The value in the dictionary is accessed using its key not by the index value.
If u try access the value with its key not available in the dictionary it will raise a keyerror.

Example:

R={ ‘Rollno’ : 1 ,’Name’ : ‘Hari’,”course’ : ‘B.Tech’}


print(“Rollno:”, R[‘Rollno’])
print(“Name:”, R[‘Name’])
print(“Name:”, R[‘dept’])

Output:

1
Hari
Traceback (most recent call last):
File "./prog.py", line 5, in <module>
KeyError: 'dept'

Adding an item in dictionary:

To a new value in dictionary specify key-value pair with the existing Dictionary name..

Syntax:
Dictionary_name[‘key’:’value’]
Example:

R={ ‘Rollno’ : 1 ,’Name’ : ‘Hari’,”course’ : ‘B.Tech’}


R[‘Mark’]=98
print( R )

Output:
Rollno’ : 1 ,’Name’ : ‘Hari’,”course’ : ‘B.Tech’ Mark:98

Modifying an item in Dictionary:


R={ ‘Rollno’ : 1 ,’Name’ : ‘Hari’,”course’ : ‘B.Tech’}
R[‘Mark’]=100
print( R )

Output:
Rollno’ : 1 ,’Name’ : ‘Hari’,”course’ : ‘B.Tech’ Mark:100

Deleting Items in Dictionary:


Using “del” keyword:
The del statement removes a key-value pair from a dictionary. For example, the
following dictionary contains the names of various fruits and the number of each fruit
in stock:

inventory={'apples':430,'bananas':312,'oranges':525,'pears':217}
print (inventory)

{'oranges':525,'apples':430,'pears':217,'bananas':312}

If someone buys all of the pears, we can remove the entry from the dictionary:

del inventory['pears']
print (inventory)
{'oranges':525,'apples':430,'bananas':312}

del also deletes the dictionary completely. for example

R = { "brand": "Ford", "model": "Mustang", "year": 1964 }


del R
print(R)

Output:
Traceback (most recent call last):
File "demo_dictionary_del3.py", line 7, in <module>
print(R) #this will cause an error because “R" no longer exists.
NameError: name ‘R' is not defined

Looping over Dictionary:

dict={'Rollno':1,'Name':'Arav','Course':'B.Tech'}
for k in dict: #Accessing keys
print(k)

Output:

Rollno
Name
Course
for k in dict.values( ): #Accessing values
print(k)

Output:
1
Arav
B.Tech

for i,j in dict.items(): #Accessing Items


print(i,j)

Output:
Rollno 1
Name Arav
Course B.Tech

Nested Dictionary:
A dictionary inside another dictionary is called nested dictionary.

student={‘Shiv’:{‘pspp’:98,’Physics’:100,’BEEE’:95},
‘Sasi’:{‘pspp’:100,’Physics’:97,’BEEE’:94},
‘Bobby’:‘pspp’:99,’Physics’:93,’BEEE’:91}}

for x,y in student.items():


print(x,y)
print(student[‘sasi’][‘ppsp’]) # Accessing specified element
from nested dictionary

Output:
Shiv {'pspp': 98, 'Physics': 100, 'BEEE': 95}
Sasi {'pspp': 100, 'Physics': 97, 'BEEE': 94}
Bobby {'pspp': 99, 'Physics': 93, 'BEEE': 91}
100
String Formatting With Dictionary:
student={'Arav':'B.Tech','Harini':'MBBS'}
for x,y in student.items():
print("%s studying in %s" % (x,y) )

Output:
Arav studying in B.Tech
Harini studying in MBBS

DICTIONARY OPERATIONS AND FUNCTIONS:

1. Membership:The ‘in’ and ‘not in’ operators on a Python dictionary to check whether it
contains a certain key.
h={1: 1, 2: 2, 3: 3}
print(2 in h)
print(4 not in h)
Output:
True
True

2. len():Returns the no of elements in the dictionary

Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}


print ("Length : " ,len (Dict) )

Output:
Length : 4

3.Sorted():Sort the dictionary in ascending order

names = {1:'Alice' ,2:'John' ,4:'Peter' ,3:'Andrew'


,6:'Ruffalo' ,5:'Chris' }
print(sorted(names.keys()))
print(sorted(names.items()))
Output:
[1, 2, 3, 4, 5, 6]
[(1, 'Alice'), (2, 'John'), (3, 'Andrew'), (4, 'Peter'), (5, 'Chris'), (6, 'Ruffalo')]
DICTIONARY METHODS:

1. fromkeys(): The dict.fromkeys() method creates a new dictionary from the given
iterable (string, list, set, tuple) as keys and with the specified value.

Syntax dictionary.fromkeys(sequence, value)

Example1:
keys = {'Mumbai','Bangalore','Chicago','New York'}
value = 'city'
dictionary = dict.fromkeys(keys, value)
print(dictionary)

Output:
{'New York': 'city', 'Bangalore': 'city', 'Mumbai': 'city', 'Chicago': 'city'}

Example2:
D = dict.fromkeys(['Bob', 'Sam'], 'Developer')
print(D)

Output:
{'Bob': 'Developer', 'Sam': 'Developer'}

2. dict():Python dict() Function is used to create a dictionary

Example 1
myDict = dict(a=1, b=2, c=3, d=4)
print(myDict)

Output:
{'a': 1, 'b': 2, 'c': 3, 'd': 4}

Example 2

myDict = dict([('a', 1), ('b', 2), ('c', 3)])


print(myDict)

Output:
{'a': 1, 'b': 2, 'c': 3}
3. pop() :Removes the item with the specified key name
K={ "brand": "Ford", "model": "Mustang", "year": 1964 }
K.pop("model")
print( K )

Output:
{'brand': 'Ford', 'year': 1964}

4. popitem():Removes the last inserted item


K={ "brand": "Ford", "model": "Mustang", "year": 1964 }
K.popitem()
print( K )

Output:
{'brand': 'Ford', 'model': 'Mustang'}

5. clear():Removes all the elements from a dictionary.


Syntax:
dictionary.clear()

car = { "brand": "Ford", "model": "Mustang", "year": 1964 }


car.clear()
print(car)

Output:
{}

6. copy():Returns a copy of the specified dictionary.

Syntax
dictionary.copy()

car = { "brand": "Ford", "model": "Mustang", "year": 1964 }


x = car.copy()
print(x)
Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
7.get():Returns the value of the item with the specified key.

Syntax
dictionary.get(keyname, value)

d = {'a': 10, 'b': 20, 'c': 30}


d.get('b')
d.get('z')
Output:
20
None

8.setdefault():Returns the value of the item with the specified key. If the key does not
exist, insert the key, with the specified value,
Syntax: dictionary.setdefault(keyname, value)

Example1:

car = { "brand": "Ford", "model": "Mustang", "year": 1964 }


x=car.setdefault("color", "white")
print(x)
print(car)
Output:
White
{ "brand": "Ford", "model": "Mustang", "year": 1964 , “color” : “white”}

Example2:
romanNums = {'I':1, 'II':2, 'III':3}
value = romanNums.setdefault('IV')
print("The return value is: ",value)
print("Updated dictionary: ",romanNums)

Output:
The return value is: None
Updated dictionary:
{'I': 1, 'II': 2, 'III': 3, 'IV': None}
9.update():Updates the dictionary with the elements from another dictionary object or
from an iterable of key/value pairs.

Syntax: dict.update(iterable)

Example 1: Update with another Dictionary


Dictionary1 = {'A': 'Apple', 'B': 'Ball' }
Dictionary2 = {'B': 'Bat'}
print("Original Dictionary:", Dictionary1)
Dictionary1.update(Dictionary2)
print("Dictionary after updation:",Dictionary1)

Output:
Original Dictionary: {'A': 'Apple', 'B': 'Ball'}
Dictionary after updation: {'A': 'Apple', 'B': 'Bat'}

Example 2: Update with an Iterable

Dictionary1 = {'A': 'Apple'}


print("Original Dictionary:", Dictionary1)
Dictionary1.update(B='ball', C='Cat')
print("Dictionary after updation:",Dictionary1)

Output:
Original Dictionary: {'A': 'Apple'}
Dictionary after updation: {'A': 'Apple', 'B': 'ball', 'C': 'Cat'}

10.items(): Returns a view object which contains the key-value pairs of the dictionary, as
tuples in a list.

Syntax: dictionary.items()

d = {'a': 10, 'b': 20, 'c': 30}


print(list(d.items()))
print(list(d.items())[1][0])
print(list(d.items())[1][1])
Output:
[('a', 10), ('b', 20), ('c', 30)]
B
20

11.keys():Returns a view object which contains the keys of the dictionary, as a list.
The view object will reflect any changes done to the dictionary, see example below.
Syntax
dictionary.keys()
car = { "brand": "Ford", "model": "Mustang", "year": 1964 }
car["color"] = "white"
x = car.keys()
print(x)

Output:
(['brand', 'model', 'year', 'color'])

12.values():Returns a view object which contains the values of the dictionary, as a list. The
view object will reflect any changes done to the dictionary, see example below.

Syntax
dictionary.values()

car = { "brand": "Ford", "model": "Mustang", "year": 1964 }


car["year"] = 2018
x = car.values()
print(x)

Output:
dict_values(['Ford', 'Mustang', 2018])

Dictionaries and Lists:


Converting a Python list to a dictionary is done using the dict.fromkeys() method,
dictionary comprehension, or the zip() method. The zip() method is useful to merge two lists
into a dictionary.

1. List to Dictionary Using dict.fromkeys():


Create a dictionary using the dict.fromkeys() method. This method accepts a list of keys that
you want to turn into a dictionary. It is optional to specify a value so as to assign to every
key.
Example:

fruits = ["Apple", "Pear", "Peach", "Banana"]


fruit_dictionary = dict.fromkeys(fruits, "In stock")
print(fruit_dictionary)

Output:
{'Apple': 'In stock', 'Pear': 'In stock', 'Peach': 'In stock', 'Banana': 'In stock'}

2. Convert List to Dictionary Python using Dictionary Comprehension:

Dictionary comprehension technique is used to convert a Python list to a dictionary using the
same values.
A dictionary comprehension is similar to a list comprehension but Dictionary
comprehensions use pointed brackets ({}) whereas list comprehensions use square brackets
([]).

Example:
fruits = ["Apple", "Pear", "Peach", "Banana"]
fruit_dictionary = { fruit : "In stock" for fruit in fruits }
print(fruit_dictionary)

Output:
{'Apple': 'In stock', 'Pear': 'In stock', 'Peach': 'In stock', 'Banana': 'In stock'}

3.Python Convert List to Dictionary using zip( ) function:

Zip( ) function to convert two lists into a dictionary. One list is used as the keys for the
dictionary and the other as the values.

Example:

fruits = ["Apple", "Pear", "Peach", "Banana"]


prices = [0.35, 0.40, 0.40, 0.28]
fruit_dictionary = dict(zip(fruits, prices))
print(fruit_dictionary)

Output:
{'Apple': 0.35, 'Pear': 0.4, 'Peach': 0.4, 'Banana': 0.28}

Dictionaries and Tuples:


1.Using dict( ) function:
A dictionary object can be constructed using dict() function. This function takes a tuple of
tuples (or list of tuples) as argument. Each tuple contains key value pair and length of the
tuple should be 2.

Example:
t=((1,'a'), (2,'b'))
print(dict(t))

Output:
{1: 'a', 2: 'b'}

Example:
t=((1,'a'), (2,'b'))
dict((y, x) for x, y in t)
print(dict(t))
Output:
{1: 'a', 2: 'b'}

2.Using dict():

You can use the combination of dict(), map(), and reversed() method to convert a tuple to the
dictionary. The map() method returns a map object, which is an iterator. The reversed()
function returns the reversed iterator of the given sequence.

Example:

tup = ((11, "eleven"), (21, "mike"), (19, "dustin"), (46,


"caleb"))
print(tup)
dct = dict(tup)
print(dct)

Output:
((11, 'eleven'), (21, 'mike'), (19, 'dustin'), (46, 'caleb'))
{11:'eleven', 21:'mike', 19:'dustin', 46:'caleb'}

3.Using setdefault() method( ):

To convert a list of tuples into a dictionary, use the setdefault() method.


The setdefault() method takes the first parameter to key and the second parameter to a value
of the dictionary.

The setdefault() function searches for a key and displays its value, and creates a new key
with def_value if the key is not present. See the following code.
Example:

x=((1,”stars”),(2,”moon”),(3,”sun”))
dict = { }
for i,j in x:
dict.setdefault(i,[]).append(j)
print(dict)

Output:
{1: [“stars”], 2: [“moon”], 3: [“sun”]}

Example:

def conversion(tup, dict):


for x, y in tup:
dict.setdefault(x, []).append(y)
return dict

tups = [("Boba", 21), ("Din", 19), ("Grogu", 46), ("Ahsoka",


11)]
dictionary = {}
print(conversion(tups, dictionary))

Output:
{'Boba': [21], 'Din': [19], 'Grogu': [46], 'Ahsoka': [11]}
{'Boba': [21], 'Din': [19], 'Grogu': [46], 'Ahsoka': [11]}
Illustrative Programs:

1.Python program for implementation of Selection sort

Working of selection sort:


1. Partition the list into sorted and unsorted sections. The sorted section is initially empty
while the unsorted section contains the entire list
2. Set the first element of the unsorted array as minimum element
3. Compare the minimum element with the second element of unsorted array. If the
second element is smaller than the first, we assign it as a minimum element.
4. Again compare the second element to the third and if the third element is smaller than
second, assign it as minimum. Repeat the process until the last element of unsorted
array is reached. Thus find the minimum value from unsorted array
5. Swap the minimum value with the first element of the unsorted array
6. Repeat steps 2 to 5 until we get the sorted array.
Program:
def selectionsort(A):
for i in range(len(A)): # Traverse all array elements
min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A[j]: # Find min
min_idx = j

A[i], A[min_idx] = A[min_idx], A[i] # Swap

A = [12, 10, 16, 11, 9, 7]


selectionsort(A)
print ("Sorted array", A)

Output:
Sorted array [7,9,10,11,12,16]
2.Python program for implementation of Insertion Sort

Steps for Insertion sort:


Step 1 − Consider first element as already sorted.
Step 2 − Pick next element
Step 3 − Compare with all elements in the sorted sub-list
Step 4 − Shift all the elements in the sorted sub-list that is greater than the
value to be sorted
Step 5 − Insert the value to be sorted in the correct position in sorted sub-list
Step 6 − Repeat from step 2 until list is sorted
Program:
def insertion_sort(x):
for i in range(1,len(x)): # Traverse through 1 to len(x)
loc=i
temp=x[loc]
while (loc>0) and x[loc-1]>temp:
x[loc]=x[loc-1] # Shift elements to the right
loc=loc-1
x[loc]=temp
return x

a=[42,33,19,55,16]
print(“Sorted array is: “, insertion_sort(a))

Output:
Sorted array is : [16,19,33,42,55]

3..Python program for implementation of merge Sort

Steps for merge sort:

1. Split the unsorted list until it contains single element in the sublist
2. Compare each of the element and group them as sorted
3. Repeat step 2 until whole list is merged and sorted
Program:

def mergeSort(nlist):
print("Splitting ",nlist)
if len(nlist)>1:
mid = len(nlist)//2
lefthalf = nlist[:mid]
righthalf = nlist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)

#merging left half and right half into a single


sorted list

i=j=k=0
while i<len(lefthalf) and j <len(righthalf):
if lefthalf[i] < righthalf[j]:
nlist[k]=lefthalf[i]
i=i+1
k=k+1
else:
nlist[k]=righthalf[j]
j=j+1
k=k+1
while i<len(lefthalf):
nlist[k]=lefthalf[i]
i=i+1
k=k+1
while j <len(righthalf):
nlist[k]=righthalf[j]
j=j+1
k=k+1
print("Merging ",nlist)
nlist = [14,46,43,27,57,41,45,21,70]
mergeSort(nlist)
print(nlist)

Output:
Splitting [14, 46, 43, 27, 57, 41, 45, 21, 70]
Splitting [14, 46, 43, 27]
Splitting [14, 46]
Splitting [14]
Splitting [46]
Merging [14, 46]
Splitting [43, 27]
Splitting [43]
Splitting [27]
Merging [27, 43]
Merging [14, 27, 43, 46]
Splitting [57, 41, 45, 21, 70]
Splitting [57, 41]
Splitting [57]
Splitting [41]
Merging [41, 57]
Splitting [45, 21, 70]
Splitting [45]
Splitting [21, 70]
Splitting [21]
Splitting [70]
Merging [21, 70]
Merging [21, 45, 70]
Merging [21, 41, 45, 57, 70]
Merging [14, 21, 27, 41, 43, 45, 46, 57, 70]
[14, 21, 27, 41, 43, 45, 46, 57, 70]

4. How to plot a histogram chart in Python

Histogram is an accurate method for the graphical representation of


numerical data distribution. It is a type of bar plot where X-axis represents the bin
ranges while Y-axis gives information about frequency.

from matplotlib import pyplot as plt


percentage = [97,54,45,10,20,10,30,97,50,71,40,49,40,74
,95,80,65,82,70,65,55,70,75,60,52,44,43,42,45]
binrange = [0,20,40,60,80,100]
plt.hist(percentage, bins=binrange, histtype='bar', rwidth=0.8)

plt.xlabel('percentage')
plt.ylabel('No.of students')
plt.title('Histogram')
plt.show()
Output:
5. Write a python program to plot a line graph

import matplotlib.pyplot as plt

Year = [1920,1930,1940,1950,1960,1970,1980,1990,2000,2010]
Unemployment_Rate = [9.8,12,8,7.2,6.9,7,6.5,6.2,5.5,6.3]

plt.plot(Year, Unemployment_Rate)
plt.title('Unemployment Rate Vs Year')
plt.xlabel('Year')
plt.ylabel('Unemployment Rate')
plt.show()

Output
6. Write a Python program to compute element-wise sum of given tuples.

x = (1,2,3,4)
y = (3,5,2,1)
z = (2,2,3,1)
print("Original lists:")
print(x)
print(y)
print(z)
print("\nElement-wise sum of the said tuples:")
result = tuple(map(sum, zip(x, y, z)))
print(result)

Output:
Original lists:
(1, 2, 3, 4)
(3, 5, 2, 1)
(2, 2, 3, 1)
Element-wise sum of the said tuples:
(6, 9, 8, 6)

7. Write a Python program convert a given string list to a tuple.

def string_list_to_tuple(str1):
result = tuple(x for x in str1 if not x.isspace())
return result
str1 = "python 3.0"
print("Original string:")
print(str1)
print(type(str1))
print("Convert the said string to a tuple:")
print(string_list_to_tuple(str1))
print(type(string_list_to_tuple(str1)))

Output:

Original string:
python 3.0
<class 'str'>
Convert the said string to a tuple:
('p', 'y', 't', 'h', 'o', 'n', '3', '.', '0')
<class 'tuple'>
8. Write a Python program to check if two given sets have no elements in
common.

x = {1,2,3,4}
y = {4,5,6,7}
z = {8}
print("Original set elements:")
print(x)
print(y)
print(z)
print("\nConfirm two given sets have no element(s) in
common:")
print("\nCompare x and y:")
print(x.isdisjoint(y))
print("\nCompare x and z:")
print(z.isdisjoint(x))
print("\nCompare y and z:")
print(y.isdisjoint(z))

Output:
Original set elements:
{1, 2, 3, 4}
{4, 5, 6, 7}
{8}

Confirm two given sets have no element(s) in common:

Compare x and y:
False

Compare x and z:
True

Compare y and z:
True

9. Write a Python program to remove the intersection of a 2nd set from the 1st
set.

sn1 = {1,2,3,4,5}
sn2 = {4,5,6,7,8}
print("Original sets:")
print(sn1)
print(sn2)
print("\nRemove the intersection of a 2nd set from the 1st set
using difference_update():")
sn1.difference_update(sn2)
print("sn1: ",sn1)
print("sn2: ",sn2)
sn1 = {1,2,3,4,5}
sn2 = {4,5,6,7,8}
print("\nRemove the intersection of a 2nd set from the 1st set
using -= operator:")
sn1-=sn2
print("sn1: ",sn1)
print("sn2: ",sn2)

Output:
Original sets:
{1, 2, 3, 4, 5}
{4, 5, 6, 7, 8}

Remove the intersection of a 2nd set from the 1st set using difference_update():
sn1: {1, 2, 3}
sn2: {4, 5, 6, 7, 8}

Remove the intersection of a 2nd set from the 1st set using -= operator:
sn1: {1, 2, 3}
sn2: {4, 5, 6, 7, 8}

10.Write a Python program to count the occurrences of letter in a string using


dictionaries.
Program:
def lettercount(str):
d={}
str=str.lower()
str="".join(str.split())

for i in str:
if i in d:
d[i]=d[i]+1
else:
d[i]=1
return d

print(lettercount("python prog"))

Output:

{'p': 2, 'y': 1, 't': 1, 'h': 1, 'o': 2, 'n': 1, 'r': 1, 'g': 1}


11.Write a recursive Python function that recursively computes sum of elements
in a list of lists.

Program:

def lsum(l):

sum=0

for i in l:

if type(i)== list:

sum=sum+lsum(i)

else:

sum=sum+i

return sum

lst=[1,2,[3,4],[5,6,7],8]

print(lsum(lst))

Output:
36

You might also like