You are on page 1of 72

Anand Komiripalem

Anand Komiripalem

List Data Type: Introduction


 If we want to represent a group of individual objects as a single entity we
can go with list.
 In List:
 insertion order preserved
 duplicate objects are allowed
 heterogeneous objects are allowed.
 List is dynamic because based on our requirement we can increase the
size and decrease the size.
 In List the elements will be placed within square brackets [] and with
comma separator.
 We can differentiate elements and preserve insertion order by using index
 Python supports both positive and negative indexes. +ve index means
from left to right where as negative index means right to left.
 List objects are mutable.
Anand Komiripalem

List Data Type: Creating List


 We can create empty list
Syntax: list=[]

Ex:
list=[]
print(list) #[]
print(type(list)) #<class ‘list’>

 list = [10, 20, 30, 40]  if we already know the elements of list
 With Dynamic Input:
Output:
list=eval(input("Enter List:"))
print(list) Enter List: [10,20,30,40]
print(type(list)) [10,20,30,40]
<class ‘list’>
Anand Komiripalem

List Data Type: Creating List


 With list() Function:
l=list(range(0,10,2)) Output:
[0, 2, 4, 6, 8]
print(l)
<class 'list'>
print(type(l))

 With split() Function:


s="Learning Python is very very easy !!!"
l=s.split()
print(l) # ['Learning', 'Python', 'is', 'very', 'very', 'easy', '!!!']
print(type(l)) # <class 'list'>
 we can take list inside another list, such type of lists are called
nested lists.
Ex: [10, 20, [30, 40]]
Anand Komiripalem

List Data Type: Accessing Elements


We can access elements of the list either by using index or by using slice
operator(:)

By using Index:
 List follows zero based index.
 List supports both +ve and -ve indexes.

Ex:
list = [10, 20, 30, 40]
print(list[0]) # 10
print(list[-1]) # 40
print(list[10]) # IndexError:
Anand Komiripalem

List Data Type: Accessing Elements


By using Slice Operator:
Syntax: list2 = list1[start:stop:step]

n=[1,2,3,4,5,6,7,8,9,10]
print(n[2:7:2]) #[3, 5, 7]
print(n[4::2]) #[5, 7, 9]
print(n[3:7]) #[4, 5, 6, 7]
print(n[8:2:-2]) #[9, 7, 5]
print(n[4:100]) #[5, 6, 7, 8, 9, 10]
Anand Komiripalem

List Data Type: Traversing


 The sequential access of each element in the list is called traversal.
By using while Loop:

n = [0,1,2,3,4,5]
i=0
while I < len(n): Output:
print(n[i])
i=i+1 1
2
3
By using for Loop:
4
n=[0,1,2,3,4,5] 5
for n1 in n:
print(n1)
Anand Komiripalem

List Data Type: Traversing


 Write a Program to display only Even Numbers from list

n=[0,1,2,3,4,5,6,7,8,9,10]
Output:
for n1 in n: 0 2
if n1%2==0: 4 6
print(n1) 8 10

 To display Elements by Index wise:

Output
A is available at +ve index 0 and at –ve index -1
l = ["A","B","C"]
B is available at +ve index 1 and at –ve index -2
x = len(l) C is available at +ve index 2 and at –ve index -3
for i in range(x):
print(l[i],"is available at +ve index: ",i ,"and at -ve index: ", i-x)
Anand Komiripalem

List Data Type: List Functions


To get information about list:
len(): Returns the number of elements present in the list
Ex: n = [10, 20, 30, 40]
print(len(n) ) 4

count(): returns the number of occurrences of specified item in the


list
Ex:
n=[1,2,2,2,2,3,3]
print(n.count(1)) #1
print(n.count(2)) #4
print(n.count(3)) #2
print(n.count(4)) #0
Anand Komiripalem

List Data Type: List Functions


index(): Returns the index of first occurrence of the specified item.
Ex:
n = [1, 2, 2, 2, 2, 3, 3]
print(n.index(1)) # 0
print(n.index(2)) #1
print(n.index(3)) #5
print(n.index(4)) #ValueError

Manipulating Elements:

append(): used to add item at the end of the list.

list=[]
list.append("A")
list.append("B")
list.append("C")
print(list) #[‘A’, ‘B’, ‘C’]
Anand Komiripalem

List Data Type: List Functions


Ex: To add all elements to list up to 100 which are divisible by 10
list=[]
for i in range(101):
if i%10==0: Output:
list.append(i) [0,10,20,30,40,50,60,70,80,90,100]
print(list)

insert(): To insert item at specified index position


n=[1,2,3,4,5]
n.insert(1,420) Output:
print(n) [1,420,2,3,4,5]
Anand Komiripalem

List Data Type: List Functions


Note: If the specified index is greater than max index then
element will be inserted at last position. If the specified index is
smaller than min index then element will be inserted at first
position.
n=[1,2,3,4,5]
n.insert(10,777)
n.insert(-10,999)
print(n) #[999,1,2,3,4,5,777]

Differences between append() and insert()


Anand Komiripalem

List Data Type: List Functions


extend(): To add all items of one list to another list
Syntax: l1.extend(l2)
Ex:
order1=["Chicken","Mutton","Fish"]
order2=["RC","KF","FO"]
order1.extend(order2)
print(order1) #['Chicken', 'Mutton', 'Fish', 'RC', 'KF', 'FO']
Ex:2
order = ["Chicken","Mutton","Fish"]
order.extend("Mushroom")
print(order)

Output: ['Chicken', 'Mutton', 'Fish', 'M', 'u', 's', 'h', 'r', 'o', 'o', 'm']
Anand Komiripalem

List Data Type: List Functions


remove(): used to remove specified item from the list. If the item is present multiple
times then only first occurrence will be removed.
n=[10,20,10,30]
n.remove(10)
print(n) #[20, 10, 30]
Note: If the specified item not present in list then we will get Error

pop(): It removes and returns the last element of the list.

n=[10,20,30,40]
print(n.pop()) #40
print(n.pop()) #30
print(n) #[10,20]

pop(index): to remove a value based on index.


Anand Komiripalem

List Data Type: List Functions


Ordering Elements of List:
reverse(): used to reverse() order of elements of list.
n=[10,20,30,40]
n.reverse()
print(n) #[40, 30, 20, 10]

sort(): sort the elements of list according to default natural sorting order
n = [20,5,15,10,0]
n.sort()
print(n) # [0,5,10,15,20]

s = ["Dog","Banana","Cat","Apple"]
s.sort()
print(s) # ['Apple','Banana','Cat','Dog']

Note: To use sort() function, compulsory list should contain only homogeneous
elements. Otherwise we will get TypeError
Anand Komiripalem

List Data Type: List Functions


To Sort in Reverse of Default Natural Sorting Order:
 We can sort according to reverse of default natural sorting order by using
reverse=True argument.
n = [40,10,30,20]
n.sort()
print(n) # [10,20,30,40]
n.sort(reverse = True)
print(n) # [40,30,20,10]
n.sort(reverse = False)
print(n) # [10,20,30,40]

clear(): removes all the elements from the list


Ex:
l=[10,20,30,40]
print(l) #[10,20,30,40]
l.clear()
print(l) #[]
Anand Komiripalem

List Data Type: Aliasing & Cloning


Aliasing : The process of giving another reference variable to the existing list
Ex:
x=[10,20,30,40]
y=x
print(id(x)) #37867608
print(id(y)) #37867608

 The problem in this approach is if we change the elements in list by using


one reference variable it will reflect in the second list automatically.
Ex:
x = [10,20,30,40]
y=x
y[1] = 777
print(x) # [10,777,30,40]
Anand Komiripalem

List Data Type: Aliasing & Cloning


 If we want to only copy the content of the list then we can create a
duplicate object of the list. This process is called cloning
 We can implement cloning by using slice operator or by using copy()
function.
By using Slice Operator:

x = [10,20,30,40]
y = x[:]
y[1] = 777
print(x) #[10, 20, 30, 40]
print(y) # [10, 777, 30, 40]
Anand Komiripalem

List Data Type: Aliasing & Cloning


using copy() Function:

x = [10,20,30,40]
y = x.copy()
y[1] = 200
print(x) # [10, 20, 30, 40]
print(y) # [10, 200, 30, 40]

Difference between (= Operator) and copy() Function


= Operator meant for aliasing
copy() Function meant for cloning
Anand Komiripalem

List Data Type: Mathematical Operations


Concatenation Operator (+): used to concatenate 2 lists into a single list
Ex:
a = [10, 20, 30]
b = [40, 50, 60]
c = a+b
print(c) # [10, 20, 30, 40, 50, 60]

Note: To use + operator compulsory both arguments should be list objects,


otherwise we will get TypeError.

Ex:
c = a+40 #TypeError:
c = a+[40] # Valid
Anand Komiripalem

List Data Type: Mathematical Operations


Repetition Operator (*): to repeat elements of list for specified
number of times.
Ex:
x = [10, 20, 30]
y = x*3
print(y) #[10, 20, 30, 10, 20, 30, 10, 20, 30]

Comparing List Objects:

==  for content comparision


 Inorder to compare two lists, both the lists should be same in length
 Order should be same
 Content should be same
Anand Komiripalem

List Data Type: Mathematical Operations


Ex:
x = [”Hai", ”Hello", ”Bye"]
y = [“Hai”, “Hello", “Bye"]
z = [“HAI", “HELLO", “BYE"]
print(x == y) # True
print(x == z) # False
print(x != z) # True

 When ever we are using relatational Operators (<, <=, >, >=) between List Objects, only
1ST Element comparison will be performed.

x = [50, 20, 30] x=[“Anand”, “Ravi”, “john”]


y = [40, 50, 60, 100, 200] y=[“Ravi”, “Hari”]
print(x>y) # True print(x>y) #False
print(x>=y) # True print(x>=y) #False
print(x<y) #False print(x<y) #True
print(x<=y) # False print(x<=y) #True
Anand Komiripalem

List Data Type: Mathematical Operations


Membership Operators:
checks whether element is a member of the list or not
 in
 not in

Ex:
n=[10,20,30,40]
print (10 in n) #True
print (10 not in n) #False
print (50 in n) #False
print (50 not in n) #True
Anand Komiripalem

List Data Type: Nested Lists


 we can take one list inside another list. Such type of lists are called
nested lists.
Ex:
n=[10,20,[30,40]]
print(n) #[10,20,[30,40]]
print(n[0]) #10
print(n[2]) #[30,40]
print(n[2][0]) #30
print(n[2][1]) #40
Anand Komiripalem

List Data Type: List Comprehensions


 It is very easy and compact way of creating list objects from another
List/Range etc based on some condition.
Syntax: list = [expression for item in list if condition]
Ex:
s = [ x*x for x in range(1,11)]
print(s) #[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

v = [2**x for x in range(1,6)]


print(v) #[2, 4, 8, 16, 32]

s = [ x*x for x in range(1,11)]


m = [x for x in s if x%2==0]
print(m) #[4, 16, 36, 64, 100]
Anand Komiripalem

List Data Type: List Comprehensions


 Create a new list with elements that are present in 1st list but not in
2nd list
num1=[10,20,30,40]
num2=[30,40,50,60]
num3=[ i for i in num1 if i not in num2]
print(num3) #[10,20]
 Program to find length of each word present in a string

words="the quick brown fox jumps over the lazy dog".split()


print(words)
l=[[w,len(w)] for w in words]
print(l)

Output: [['the', 3], ['quick', 5], ['brown', 5], ['fox', 3], ['jumps', 5],
['over', 4], ['the', 3], ['lazy', 4], ['dog', 3]]
Anand Komiripalem

List Data Type: Example


 Write a Program to display Unique Vowels present in the given
Word?

vowels=['a','e','i','o','u']
word=input("Enter the word to search for vowels: ")
found=[]
for letter in word:
if letter in vowels:
if letter not in found:
found.append(letter)
print(found)
print("different vowels present in",word,"are",found)
Anand Komiripalem

Tuple
Data Type
Anand Komiripalem

Tuple Data Type


 Tuple is exactly same as List except that it is immutable. i.e once we
creates Tuple object, we cannot perform any changes in that object.
 Tuple is Read only version of List.
 If our data is fixed and never changes then we should go for Tuple.
 Insertion Order is preserved
 Duplicates are allowed
 Heterogeneous objects are allowed.
 We can preserve insertion order and we can get the values by using
index.
 Tuple support both +ve and -ve index. +ve index means forward
direction (from left to right) and -ve index means backward direction
(from right to left)
Anand Komiripalem

Tuple Data Type


 We can represent Tuple elements within Parenthesis and with comma
separator.
 Parenthesis are optional but recommended to use.
Ex:
t=10,20,30,40
print(t) #(10,20,30,40)
print(type(t)) #<class ‘tuple’>

Note: We have to take special care about single valued tuple. compulsory
the value should ends with comma, otherwise it is not treated as
tuple, it will be considered as int
Ex:
t=(10)
print(t) # 10
print(type(t)) #<class ‘int’>
Anand Komiripalem

Tuple Data Type


Note: if we want to declare a tuple with single element init then the
element have to end with comma
Ex:
t=(10,)
print(t) #(10)
print(type(t)) #<class ‘tuple’>

Tuple Creation:
t = (): Creating an empty tuple
t = (value,): Creation of Single valued Tuple, Parenthesis are Optional,
should ends with Comma
t = 10, 20, 30: Creation of multi values Tuples & Parenthesis are
Optional.
Anand Komiripalem

Tuple Data Type


tuple() Function:
list=[10,20,30]
t=tuple(list)
print(t) #(10,20,30)

t=tuple(range(10,20,2))
print(t) #(10,12,14,16,18,20)

Accessing Elements of Tuple:


We can access either by index or by slice operator
using Index:

t = (10, 20, 30, 40, 50, 60)


print(t[0]) #10
print(t[-1]) # 60
print(t[100]) # IndexError: tuple index out of range
Anand Komiripalem

Tuple Data Type:


using Slice Operator:

t=(10,20,30,40,50,60)
print(t[2:5]) #(30,40,50)
print(t[2:100]) #(30,40,50,60)
print(t[::2]) #(10,30,50)
Anand Komiripalem

Tuple Data Type: Mathematical Operations


Mathematical Operators for Tuple:
Concatenation Operator (+):
t1=(10,20,30)
t2=(40,50,60)
t3=t1+t2
print(t3) # (10,20,30,40,50,60)

Multiplication Operator OR Repetition Operator (*):


t1=(10,20,30)
t2=t1*3
print(t2) # (10,20,30,10,20,30,10,20,30)
Anand Komiripalem

Tuple Data Type: Tuple Functions


len(): To return number of elements present in the tuple.
Ex:
t = (10,20,30,40)
print(len(t)) #4

count(): returns number of occurrences of given element in the tuple


Ex:
t = (10, 20, 10, 10, 20)
print(t.count(10)) #3

sorted(): sort elements based on default natural sorting order


Ex:
t=(40,10,30,20)
t1=sorted(t)
print(t1) #(10,20,30,40)
print(t) #(40,10,30,20)
Anand Komiripalem

Tuple Data Type: Tuple Functions


 We can sort according to reverse of default natural sorting order as
follows
t1 = sorted(t, reverse = True)
print(t1) # [40, 30, 20, 10]

min(), max():
returns min and max values according to default natural sorting order.
t = (40,10,30,20)
print(min(t)) # 10
print(max(t)) # 40
Anand Komiripalem

Tuple Data Type


Tuple Packing and Unpacking:
We can create a tuple by packing a group of variables.
a = 10
b = 20
c = 30
d = 40
t = a, b, c, d
print(t) #(10, 20, 30, 40)
 Tuple unpacking is the reverse process of Tuple packing.
 We can unpack a Tuple and assign its values to different variables.
t=(10,20,30,40)
a,b,c,d=t
print("a=",a,"b=",b,"c=",c,"d=",d) #a= 10 b= 20 c= 30 d= 40
Anand Komiripalem

Tuple Data Type


Note: At the time of tuple unpacking the number of variables and number of
values should be same, otherwise we will get ValueError.
Ex:
t = (10,20,30,40)
a, b, c = t # ValueError:

Tuple Comprehension:
 Tuple Comprehension is not supported by Python.
t = ( x**2 for x in range(1,6))
 Here we are not getting tuple object and we are getting generator object.
t= ( x**2 for x in range(1,6))
print(type(t)) #<class ‘generator’>
for x in t:
print(x) #1,4,9,16,25
Anand Komiripalem

Tuple Data Type


 Write a Program to take a Tuple of Numbers from the Keyboard
and Print its Sum and Average?

t=eval(input("Enter Tuple of Numbers:"))


l=len(t)
sum=0
for x in t: Output:
sum=sum+x Enter Tuple of Numbers:
print("The Sum=",sum) (10,20,30,40)
print("The Average=",sum/l) The Sum= 100
The Average= 25.0
Anand Komiripalem

Set
Data Type
Anand Komiripalem

Set Data Type


 Used to represent a group of unique values as a single entity

 In Set:
 Duplicates are not allowed.
 Insertion order is not preserved. But we can sort the elements.
 Indexing and slicing not allowed for the set.
 Heterogeneous elements are allowed.
 Set objects are mutable
 We can represent set elements within curly braces and with comma
separation
Anand Komiripalem

Set Data Type


Creation of Set:
1st way:
s={10,20,30,40}
print(s) #{10,20,30,40}
print(type(s)) #<class ‘set’>
2nd Way:
We can create set objects by using set() Function
Syntax: s = set(any sequence)

l = [10,20,30,40,10,20,10]
s=set(l)
print(s) # {40, 10, 20, 30}
---------------------------------------------------
s=set(range(5))
print(s) #{0, 1, 2, 3, 4}
Anand Komiripalem

Set Data Type


Creating an empty set:
 We have to use set() function to create an empty set.
s=set()
print(s) #set()
print(type(s)) #<class ‘set’>

 We cannot use empty braces ({} ) to create an empty set. {}


represents a dictionary not set
s={}
print(s) #{}
print(type(s)) #<class ‘dict’>
Anand Komiripalem

Set Data Type: Functions


add(x): to add an element to set
s={10,20,30}
s.add(40)
print(s) #{40, 10, 20, 30}

update(x,y,z):
 To add multiple items to the set.
 Arguments are not individual elements and these are Iterable
objects like List, Range etc.
s={10,20,30}
l=[40,50,60,10]
s.update(l,range(5))
print(s) #{0,1,2,3,4,40,10,50,20,60,30}
Anand Komiripalem

Set Data Type: Functions


copy(): to clone the set object, only the elements will be copied but both
objects will be different
s = {10,20,30}
s1 = s.copy()
print(s1) # {10,20,30}
print(id(s))#47072600
print(id(s1)) #47071520

pop(): removes and returns some random elements from the set
s={40,10,30,20}
print(s.pop()) # 40
print(s) #{20,10,30}

Note: if we try to pop() an empty set it will give an error


Anand Komiripalem

Set Data Type: Functions


remove(x): removes specified element from the set.
s = {40, 10, 30, 20}
s.remove(30)
print(s) #{40,10,20}
Note: if we try to remove an element not in the set, it gives error

discard(x): removes the specified element from the set. if we try to


remove an element not in the set, it wont give any error
s = {10, 20, 30}
s.discard(10)
print(s) #{20, 30}
s.discard(50)
print(s) #{20, 30}
Anand Komiripalem

Set Data Type: Functions


clear(): remove all elements from the Set.
s={10,20,30}
s.clear()
print(s) #set()

Mathematical Operations on the Set:


union(): used for combining two sets
x.union(y) OR x|y.

x = {10, 20, 30, 40}


y = {30, 40, 50, 60}
print (x.union(y)) # {10, 20, 30, 40, 50, 60}
print (x|y) # {10, 20, 30, 40, 50, 60}
Anand Komiripalem

Set Data Type: Functions


intersection(): displays only common values from both the sets
x.intersection(y) OR x&y.

x = {10, 20, 30, 40}


y = {30, 40, 50, 60}
print (x.intersection(y)) # {40, 30}
print(x&y) # {40, 30}

difference(): Returns the elements present in x but not in y.


x.difference(y) OR x-y.

x = {10, 20, 30, 40}


y = {30, 40, 50, 60}
print (x.difference(y)) #{10, 20 }
print (x-y) # {10, 20}
print (y-x) # {50, 60}
Anand Komiripalem

Set Data Type: Functions


symmetric_difference(): Returns elements present in either x OR y but
not in both
x.symmetric_difference(y) OR x^y.

x = {10, 20, 30, 40}


y = {30, 40, 50, 60}
print (x.symmetric_difference(y)) #{10, 50, 20, 60}
print(x^y) #{10, 50, 20, 60}

difference_update(): updates the first Set with the Set difference.


x.difference_update(y)
x = {10, 20, 30, 40}
y = {30, 40, 50, 60}
print (x.difference_update(y)) #{10, 20}
Anand Komiripalem

Set Data Type: Functions


intersection_update(): updates the first set with only common values in
both the sets
Intersection_update()

x={20,40,50}
Y={50, 20, 10, 30}
x.intersection_update(y)
print(x) #{40}

isdisjoint():
 Two sets are said to be disjoint when their intersection is null. In simple
words they do not have any common element in between them.
 returns Trueif the two sets are disjoint.
 returns Falseif the twos sets are not disjoint.
Anand Komiripalem

Set Data Type: Functions


x={10,20,40,50}
y={30,60,70,80}
z={10,40,90,100}
print(x.isdisjoint(y)) #True
print(x.isdisjoint(z)) #False

issubset(): returns True if all elements of a set are present in another set. If not, it returns
False.
Issuperset(): returns true if all the elements of another set are present in the set if not
false.

x={10,20,30}
y={10,20,30,40,50}
print(x.issubset(y)) #True
print(y.issubset(x)) #False
print(y.issubset(y)) #True
print(y.issuperset(x)) #True
Anand Komiripalem

Set Data Type: Functions


symmetric_difference_update(): updates the original set by removing items
that are common in both sets, and inserts the items from another ser.

x={10,20,30}
y={10,20,30,40,50}
x.symmetric_difference_update(y)
print(y)

Membership Operators: (in, not in) :

s=set(“anand")
print(s) #{‘a’, ‘n’, ‘a’, ‘n’, ‘d’}
print('d' in s) #True
print('z' in s) #False
Anand Komiripalem

Set Data Type: Comprehension

s = {x*x for x in range(5)}


print (s) # {0, 1, 4, 9, 16}

s = {2**x for x in range(2,10,2)}


print (s) # {16, 256, 64, 4}
------------------------------------------------------------------------------
 Write a Program to Print different Vowels Present in the given Word?
Output:
w=input("Enter string: ") Enter String:
s=set(w) anandkomiripalem
v={'a','e','i','o','u'}
d=s.intersection(v) {a,o,I,e}
print("The vowel present in",w,"are",d)
Anand Komiripalem

Set Data Type


 Write a Program to eliminate Duplicates Present in the List?

l=eval(input("Enter List of values: ")) Output:


s=set(l)
Enter List of values:
print(s) [10,20,30,10,20,40]
{40, 10, 20, 30}

l=eval(input("Enter List of values: "))


l1=[] Output:
for x in l:
if x not in l1: Enter List of values:
[10,20,30,10,20,40]
l1.append(x)
[40, 10, 20, 30]
print(l1)
Anand Komiripalem

Dictionary
Data Type
Anand Komiripalem

Dictionary Data Type


 If we want to hold a group of objects as key-value pairs then we
should go for dictionary
 Generally used for mapping keys with values
 Dictionaries are dynamic in nature and mutable
 supports heterogeneous objects
 Insertion order is not preserved
 In key – value pair, keys cannot be duplicated but values can be
duplicated
 Indexing and slicing is not applicable in dictionary
Ex:
rollno ---- name
phone number -- address
ipaddress --- domain name
Anand Komiripalem

Dictionary Data Type


Creating a dictionary:
d = {} (or) d = dict() : for creating an empty dictionary

d= {key: value, key: value}: if we know the data in advance

Ex:
d= {1:”hai”, 2:”hello”, 3:”bye”}

Adding values to dictionary:


d={}
d[1]=“Anand”
d[2]=“Ravi”
print(d) #{1:”Anand”, 2: “Ravi”}
Anand Komiripalem

Dictionary Data Type


Accessing elements from dictionary:
by using keys
Ex:
d = {1:anand',2:'ravi', 3:’raghu'}
print(d[1]) #anand
print(d[3]) #raghu

Note: If the specified key is not available then we will get KeyError
Ex:
d = {1:anand',2:'ravi', 3:’raghu'}
print(d[1]) #anand
print(d[3]) #raghu
print(d[6]) #Error
Anand Komiripalem

Dictionary Data Type


 Write a Program to Enter Name and Percentage Marks in a
Dictionary and Display Information on the Screen
rec={}
n=int(input("Enter number of students: "))
i=1 Output:
while i <=n:
Enter number of students: 2
name=input("Enter Student Name: ")
Enter Student Name: hai
marks=input("Enter % of Marks of Student: ") Enter % of Marks of Student: 30
rec[name]=marks Enter Student Name: hello
i=i+1 Enter % of Marks of Student: 300
print(rec)
print("Name of Student","\t","% of marks") {'hai': '30', 'hello': '300'}
Name of Student % of marks
for x in rec:
hai 30
print("\t",x,"\t\t",rec[x]) hello 300
Anand Komiripalem

Dictionary Data Type


Updating a Dictionary:
d[key] = value

 If the key is not available then a new entry will be added to the
dictionary with the specified key-value pair
 If the key is already available then old value will be replaced with
new value.
d={1:"anand",2:"ravi",3:"raghu"}
d[4]="pavan"
print(d) #{1: 'anand', 2: 'ravi', 3: 'raghu', 4: 'pavan'}
d[1]="sunny"
print(d) #{1: 'sunny', 2: 'ravi', 3: 'raghu', 4: 'pavan'}
Anand Komiripalem

Dictionary Data Type


Deleting Elements from Dictionary:

del d[key]:
 It deletes entry associated with the specified key.
 If the key is not available then we will get KeyError.
d={1:"anand",2:"ravi",3:"raghu", 4:"pavan"}
del d[2]
print(d) #{1: 'anand', 3: 'raghu', 4: 'pavan'}
del d[6] #keyerror

clear(): removes all the entries from the dictionary.


d={1:"anand",2:"ravi",3:"raghu", 4:"pavan"}
d.clear()
print(d) #{ }
Anand Komiripalem

Dictionary Data Type


del dict-name: deletes dictionary completely, we cannot access
dictionary

d={1:"anand",2:"ravi",3:"raghu", 4:"pavan"}
del d
print(d) #NameError
Anand Komiripalem

Dictionary Data Type: Functions


Functions in Dictionary:

dict(): To create a dictionary

d = dict({100:"durga",200:"ravi"})  It creates dictionary with specified elements


d = dict([(100,"durga"),(200,"shiva"),(300,"ravi")]) It creates dictionary with the
given list of tuple elements

len() : Returns the number of items in the dictionary.


d={1:"anand",2:"ravi",3:"raghu", 4:"pavan"}
print(len(d)) #4
Anand Komiripalem

Dictionary Data Type: Functions


clear(): To remove all elements from the dictionary.
d={1:"anand",2:"ravi",3:"raghu", 4:"pavan"}
d.clear()
print(d) #{ }

get(key): To get the value associated with the key


 If the key is available then returns the corresponding value otherwise returns None. It
wont raise any error.
get(key,defaultvalue): If the key is available then returns the corresponding value
otherwise returns default value.

d={1:"anand",2:"ravi",3:"raghu", 4:"pavan"}
print(d) #{1: 'anand', 2: 'ravi', 3: 'raghu', 4: 'pavan'}
print(d.get(2)) #ravi
print(d.get(23)) #None
print(d.get(3,"hai")) #raghu
print(d.get(23,"hai")) #hai
Anand Komiripalem

Dictionary Data Type: Functions


pop(key): removes the entry associated with the specified key and returns
the corresponding value, if the item is not available it gives error
d={1:"anand",2:"ravi",3:"raghu", 4:"pavan"}
print(d) #{1:"anand",2:"ravi",3:"raghu", 4:"pavan"}
print(d.pop(2)) #ravi
print(d) #{1:"anand",3:"raghu", 4:"pavan"}
print(d.pop(34)) #Error

popitem(): it removes an key-value item from the dictionary and returns it.
d={1:"anand",2:"ravi",3:"raghu", 4:"pavan"}
print(d) #{1:"anand",2:"ravi",3:"raghu", 4:"pavan"}
print(d.popitem()) # 4:"pavan”
print(d) #{1:"anand",2:"ravi",3:"raghu"}
print(d.popitem()) #3:"raghu”
Anand Komiripalem

Dictionary Data Type: Functions


Keys(): gives all the keys associated with the directory
Ex:
d={1:"anand",2:"ravi",3:"raghu", 4:"pavan"}
print(d.keys()) #dict_keys([1, 2, 3, 4])
for k in d.keys():
print(k, end=“,”) #1,2,3,4

values(): gives all the values associated with dictionary


Ex:
d={1:"anand",2:"ravi",3:"raghu", 4:"pavan"}
print(d.values()) #dict_values(['anand', 'ravi', 'raghu', 'pavan'])
for k in d.values():
print(k,end=",") #anand,ravi,raghu,pavan,
Anand Komiripalem

Dictionary Data Type: Functions


items(): gives a list tuples representing the key value pair
[(k,v),(k,v),(k,v)]
d={1:"anand",2:"ravi",3:"raghu", 4:"pavan"}
print(d.items()) #dict_items([(1, 'anand'), (2, 'ravi'), (3, 'raghu'), (4, 'pavan')])
for k,v in d.items():
print(k,"---", v) #1 --- anand, 2 --- ravi, 3 --- raghu, 4 --- pavan

copy(): create exactly duplicate dictionary

d={1:"anand",2:"ravi",3:"raghu", 4:"pavan"}
d1=d.copy()
print(d1) #{1: 'anand', 2: 'ravi', 3: 'raghu', 4: 'pavan'}
print(id(d)) #46602688
print(id(d1)) #47325376
Anand Komiripalem

Dictionary Data Type: Functions


setdefault(key, value):
 If the key is already available then this function returns the corresponding value.
 If the key is not available then the specified key-value will be added as new item
to the dictionary.
d={1:"anand",2:"ravi",3:"raghu", 4:"pavan"}
d.setdefault(2,"hai")
print(d) #{1: 'anand', 2: 'ravi', 3: 'raghu', 4: 'pavan'}
d.setdefault(21,"hai")
print(d) #{1: 'anand', 2: 'ravi', 3: 'raghu', 4: 'pavan', 21: 'hai'}

d.update(x): All items present in the dictionary x will be added to dictionary d


d={1:"anand",2:"ravi",3:"raghu", 4:"pavan"}
d1={10:"sri", 11:"hello"}
d.update(d1)
print(d) #{1: 'anand', 2: 'ravi', 3: 'raghu', 4: 'pavan', 10: 'sri', 11: 'hello'}
Anand Komiripalem

Dictionary Data Type: Examples


Write a Program to take Dictionary from the Keyboard and print the Sum of
Values?
Output:
d=eval(input("Enter dictionary:"))
s=sum(d.values()) Enter dictionary:{'a':10,'b':30,'c':40}
Sum= 80
print("Sum= ",s)

Write a Program to find Number of Occurrences of each Letter present in the


given String?
Output:
word=input("Enter any word: ") Enter any word: abcaddbbacdaaac
d={} a occurred 6 times
for x in word: b occurred 3 times
d[x]=d.get(x,0)+1 c occurred 3 times
for k,v in d.items(): d occurred 3 times
print(k,"occurred ",v," times")
Anand Komiripalem

Dictionary Data Type: Examples


• Write a Program to find Number of Occurrences of each Vowel present in the
given String?

word=input("Enter any word: ")


vowels={'a','e','i','o','u'} Output:
d={} Enter any word: hai how are you
a occurred 2 times
for x in word:
e occurred 1 times
if x in vowels: i occurred 1 times
d[x]=d.get(x,0)+1 o occurred 2 times
for k,v in sorted(d.items()): u occurred 1 times
print(k,"occurred ",v," times")
Anand Komiripalem

Dictionary Data Type: Examples


Write a Program to accept Student Name and Marks from the Keyboard and create a Dictionary. Also
display Student Marks by taking Student Name as Input?

n=int(input("Enter the number of students: "))


d={}
for i in range(n):
name=input("Enter Student Name: ")
marks=input("Enter Student Marks: ")
d[name]=marks
while True:
name=input("Enter Student Name to get Marks: ")
marks=d.get(name,-1)
if marks== -1:
print("Student Not Found")
else:
print("The Marks of",name,"are",marks)
option=input("Do you want to find another student marks[Yes|No]")
if option=="No":
break
print("Thanks for using our application")
Anand Komiripalem

Dictionary Data Type: comprehensions


squares={x:x*x for x in range(1,6)}
print(squares) #{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
doubles={x:2*x for x in range(1,6)}
print(doubles) #{1: 2, 2: 4, 3: 6, 4: 8, 5: 10}

You might also like