Python Week-3
Python Week-3
Python Week-3
Department of CSE
CRT
Python Programming
Week-3
Topics:
Sets
o Properties
o Methods
Dictionary
o Properties
o Methods
Sets:
• Sets is another data structure supported by Python. Basically, sets are same as lists but
with a difference that sets are lists with no duplicate entries.
• Technically, a set is a mutable. This means that we can easily add or remove items
from it.
• A set is created by placing all the elements inside curly brackets {}, separated by
comma or by using the built-in function set().
• Syntax for creating a set:
Set_variable={val1, val2,…}
• Example: To create a set:
• A set is an unordered collection of elements, which means the order of items within a
set need not be preserved.
• Example:
• st = {1,2,3,4,5}
• When we print st, {1,2,3,4,5} may not be printed in order, but all the values will be
printed definitely without any duplicates.
• Set items cannot be accessed using indices.
Program:
st={1,2,'cse','ece',2,3,'cse'}
print(st)
Sample output:
{1, 2, 3, 'cse', 'ece'}
Program:
t=(1,2,'cse','ece',2,3,'cse')
st=set(t) #converts tuple to set
print(t)
print(st)
Sample output:
(1, 2, 'cse', 'ece', 2, 3, 'cse')
{1, 2, 3, 'ece', 'cse'}
Set Methods:
Method Description
any() Returns True if any of the elements in the set are True, False
otherwise. Returns False if the set is empty.
intersection_update() Removes the items in this set that are not present in other,
specified set(s)
isdisjoint() Returns whether two sets have a intersection or not
symmetric_difference_update() inserts the symmetric differences from this set and another
update() Update the set with another set, or any other iterable
Dictionary:
• Dictionary is a data structure in which we store items as a pair of key and value.
• Each key is separated from its value by a colon (:), and consecutive items are
separated by commas.
• The entire items in a dictionary are enclosed in curly brackets{}.
• The syntax for defining a dictionary is:
dictionary_name = {key_1: value_1, key_2: value_2, key_3: value_3,…}
Example:
d={'rollno':101,'name':'ram','percent':75.4}
print(d)
Output:
{'rollno': 101, 'name': 'ram', 'percent': 75.4}
Program:
d={'rollno':101,'name':'ram','percent':75.4}
print(d['rollno'])
print(d['name'])
print(d['percent'])
Sample output:
101
ram
75.4
Adding items:
Items to a dictionary can be added directly by using key, value pair:
syntax:
dictionary_name[key] = value
Program:
d={'rollno':101,'name':'ram','percent':75.4}
d['dept']='cse‘ #adding key, value pair
print(d)
Sample output:
{'rollno': 101, 'name': 'ram', 'percent': 75.4, 'dept': 'cse'}
Modifying value:
Value in a dictionary can be modified directly by using its key.
syntax:
dictionary_name[key] = value
Program:
d={'rollno':101,'name':'ram','percent':75.4}
d['percent']='85.9'
print(d)
Sample output:
{'rollno': 101, 'name': 'ram', 'percent': '85.9'}
Dictionary Methods:
keys()
The method keys() returns a list of all the available keys in the dictionary.
Example
dict={'Name':'Harry','Rollno':30,'Dept':'cse','Marks':97}
print(dict.keys())
Output
dict_keys(['Name', 'Rollno', 'Dept', 'Marks'])
items()
This method returns a list of dictionary's (key, value) as tuple.
Example
dict={'Name':'Harry','Rollno':30,'Dept':'cse','Marks':97}
print(dict.items())
Output
dict_items([('Name', 'Harry'), ('Rollno', 30), ('Dept', 'cse'), ('Marks', 97)])
values()
This method returns list of dictionary dictionary's values from the key value pairs.
Example
dict={'Name':'Harry','Rollno':30,'Dept':'cse','Marks':97}
print(dict.values())
Output
dict_values(['Harry', 30, 'cse', 97])
pop()
The method pop(key) Removes and returns the value of specified key.
Example
dict={'Name':'Harry','Rollno':30,'Dept':'cse','Marks':97}
dict.pop('Marks')
print(dict)
Output
{'Name': 'Harry', 'Rollno': 30, 'Dept': 'cse'}
popitem()
The popitem() method removes the item that was last inserted into the dictionary. In versions
before 3.7, the popitem() method removes a random item.
Example:
car = { "brand": "Suzuki", "model": "Swift", "year": 2020}
x = car.popitem()
print(x)
Output:
('year',2020)
copy()
This method Returns a shallow copy of dictionary.
Example
dict={'Name':'Harry','Rollno':30,'Dept':'cse','Marks':97}
dict_new=dict.copy()
print(dict_new)
Output
{'Name': 'Harry', 'Rollno': 30, 'Dept': 'cse', 'Marks': 97}
clear()
The method clear() Removes all elements of dictionary.
Example
dict={'Name':'Harry','Rollno':30,'Dept':'cse','Marks':97}
dict.clear()
print(dict)
Output
{}
get()
This method returns value of given key or None as default if key is not in the dictionary.
Example
dict={'Name':'Harry','Rollno':30,'Dept':'cse','Marks':97}
print('\nName: ', dict.get('Name'))
print('\nAge: ', dict.get('Age'))
Output
Name: Harry
Age: None
update()
The update() inserts new item to the dictionary.
Example
dict={'Name':'Harry','Rollno':30,'Dept':'cse','Marks':97}
dict.update({'Age':22})
print(dict)
Output
{'Name': 'Harry', 'Rollno': 30, 'Dept': 'cse', 'Marks': 97, 'Age': 22}
setdefault()
The setdefault() method returns the value of the item with the specified key. If the key
does not exist, insert the key, with the specified value.
Example:
car = { "brand": "Suzuki", "model": "Swift", "year": 2020}
x=car.setdefault ('model','VXi')
print(x)
Output:
Swift
which is nothing but dict[list[i]] = list[i+1], where i is every alternative index from starting to
ending of list.
Program:
l=list(input().split(","))
d={}
for i in range(0,len(l),2):
d[l[i]]=l[i+1]
print(d)
Output:
rollno,101,name,ram,marks,76
{'rollno': '101', 'name': 'ram', 'marks': '76'}
MCQs
Programs
1. Common items(sets)
A and B went to market for buying daily vegetables individually.after returning to the home
they checked out which items were similar.(lists)
Input Format
list1 as input
list2 as input
Constraints
both lists should not be empty
Output Format
list as output
Sample Input 0
Red Green Orange White Green White
Black Green White Pink White
Sample Output 0
['Green', 'White']
Sample Input 1
Red Green Orange White
Black Pink
Sample Output 1
[]
2. Symmetric differences(sets)
A and B went to supermarket purchasing some items. now print only A itmes or only print
only B items but not both.(sets)
Input Format
list1 as input list2 as input
Constraints
.
Output Format
list as output
Sample Input 0
12345
42789
Sample Output 0
[1, 3, 5, 7, 8, 9]
Sample Input 1
apple orange mango banana
grape orange banana guava
Sample Output 1
['apple', 'mango', 'grape', 'guava']
7. Value_Sorting (Dictionary)
To sort the different subject marks (Dictionary)
Input Format
list as a input
Constraints
.
Output Format
dictinoary as output
Sample Input 0
maths 20 science 10 english 3
Sample Output 0
english 3
science 10
maths 20
Sample Input 1
a 100 b 40 c 30 d 43 f 40
Sample Output 1
c 30
b 40
f 40
d 43
a 100
8. Key_Sorting ( Dictionary)
Dictionary is a pair of key and value.now we want to sort the data in dictionary based on
key.(Dictionary)
Input Format
list as input
Constraints
.
Output Format
display the sorted data in dictionary one by one.
Sample Input 0
80 krishna 60 abc 50 uma
Sample Output 0
50: uma
60: abc
80: krishna
Sample Input 1
10 20 50 70 40 20
Sample Output 1
10: 20
40: 20
50: 70