Python Week-3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

RAGHU ENGINEERING COLLEGE (A)

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

add() Adds an element to the set

all() Returns True if all elements in the set are True,

False otherwise. Returns True if the set is empty.

any() Returns True if any of the elements in the set are True, False
otherwise. Returns False if the set is empty.

clear() Removes all the elements from the set

copy() Returns a copy of the set

difference() Returns a set containing the difference between two or more


sets
difference_update() Removes the items in this set that are also included in another,
specified set
discard() Remove the specified item

intersection() Returns a set, that is the intersection of two other sets

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

issubset() Returns whether another set contains this set or not

issuperset() Returns whether this set contains another set or not

max(s) Returns the maximum value in a set.

min(s) Returns the minimum value in a set.

pop() Removes an element from the set

remove() Removes the specified element

sum(s) Returns the sum of elements in a set.

symmetric_difference() Returns a set with the symmetric differences of two sets

symmetric_difference_update() inserts the symmetric differences from this set and another

union() Return a set containing the union of sets

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

Reading dictionary at run time:


• First step in reading a dictionary is to read all the elements into a list.

• Now to create a dictionary from this list:


– starting from first element every alternative element should be a key.
– starting from second element every alternative element should be a value.

• This can be done by using the loop:


for i in range(0,len(list),2):
dict[key] = value
consider, list = [rollno,101,name,ram,marks,76]
From this list to create a dictionary, we need to assign key value pairs as shown below:
dict[‘rollno’] = 101 or dict[list[0]] = list[1]
dict[‘name’] = ‘ram’ or dict[list[2]] = list[3]
dict[‘marks’] = 76 or dict[list[4]] = list[5]

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

testmoz.com/8823852- Sets and Dictionary

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']

3. Remove duplicate items(sets)


Peter has a list containing items and he wants to find out the unique items
Input Format
list of items separated by spaces
Constraints
list of items >1
Output Format
display unique items
Sample Input 0
13211332245
Sample Output 0
[1, 3, 2, 4, 5]

4. SUM of values (Dictionary)


Dictinary having a key and value pair, to find the sum of all values in a dictionary
Input Format
dictinoary as a input
Constraints
.
Output Format
number as a output
Sample Input 0
name 23 ss 44
Sample Output 0
67
Sample Input 1
krishna 45 uma 78
Sample Output 1
123

5. Deleting key with duplicate values (Dictionary)


Deleting keys with duplicate values
Input Format
list of dictionary items separated by spaces
Constraints
Dictionary should not be empty
Output Format
Dictionary items with out duplicate values
Sample Input 0
eng 66 m1 54 m2 44 phy 54 che 37 cp 44
Sample Output 0
eng 66 che 37
Sample Input 1
eng 68 m1 89 m2 94 phy 54 che 66 cp 44
Sample Output 1
eng 68 m1 89 m2 94 phy 54 che 66 cp 44

6. Max -Value- Key (Dictionary)


To find the key index of max value of a dictionary (Dictionary)
Input Format
list as a input
Constraints
.
Output Format
key as the output
Sample Input 0
maths 85 science 35 social 45
Sample Output 0
maths
Sample Input 1
a 42 b 42 c 42 d 42
Sample Output 1
a

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

9. Topper of the Batch (Dictionary)


There are some students in a class. Each student having some marks for each subject. and
finally teacher wants to know who is the topper of the class(Dictionary)
Input Format
list as input for names of the student list as input for subjects and marks
Constraints
marks should not be negitive and not more than 100
Output Format
key as the output and number as the ouput
Sample Input 0
a1 a2 a3
s1 20 s2 40 s3 50
s1 40 s2 50 s3 60
s1 20 s2 60 s3 80
Sample Output 0
a3 160
Sample Input 1
krishna uma koushik
m1 100 m2 60 m3 40
m1 30 m2 50 m3 70
m1 100 m2 90 m3 80
Sample Output 1
koushik 270

10. Convert dictionary elements in to string form (Dictionary)


Convert dictionary elements in to string form
Input Format
List of dictionary items separated by spaces
Constraints
Dictionary can not be empty
It contains atleast one or more items
Output Format
List of items in string form
Sample Input 0
501 CSE 201 EEE 101 CIVIL 301 MECH 401 ECE
Sample Output 0
['501:CSE', '201:EEE', '101:CIVIL', '301:MECH', '401:ECE']
Sample Input 1
RNO 12 501 CSE Name shankar height 165.79
Sample Output 1
['RNO:12', '501:CSE', 'Name:shankar', 'height:165.79']
Sample Input 2
name uma age 25 gender m
Sample Output 2
['name:uma', 'age:25', 'gender:m']

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy