0% found this document useful (0 votes)
68 views

Lecture4 Py

Dictionaries in Python store data as key-value pairs and are unordered, mutable collections that do not allow duplicate keys. Sets are collections of unique and immutable elements. The document provides examples of using dictionaries and sets in Python including storing data, accessing values, and common dictionary and set methods.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views

Lecture4 Py

Dictionaries in Python store data as key-value pairs and are unordered, mutable collections that do not allow duplicate keys. Sets are collections of unique and immutable elements. The document provides examples of using dictionaries and sets in Python including storing data, accessing values, and common dictionary and set methods.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Dictionary in Python

Dictionaries are used to store data values in key:value pairs

ge
They are unordered, mutable(changeable) & don’t allow duplicate keys

le
Col
na
“key” : value

Ap
dict[”name”], dict[”cgpa”], dict[”marks”]

dict[”key”] = “value” #to assign or add new


Dictionary in Python
Nested Dictionaries

lege
Col
pna
A
student[”score”][”math”]
Dictionary Methods
myDict.keys( ) #returns all keys

lege
ol
myDict.values( ) #returns all values

na C
p
myDict.items( ) #returns all (key, val) pairs as tuples

A
myDict.get( “key““ ) #returns the key according to value

myDict.update( newDict ) #inserts the specified items to the dictionary


Set in Python
Set is the collection of the unordered items.

ge
Each element in the set must be unique & immutable.

olle
nums = { 1, 2, 3, 4 }

na C
set2 = { 1, 2, 2, 2 }

Ap
#repeated elements stored only once, so it resolved to {1, 2}

null_set = set( ) #empty set syntax


Set Methods
set.add( el ) #adds an element

lege
ol
set.remove( el ) #removes the elem an

na C
p
set.clear( ) #empties the set

A
set.pop( ) #removes a random value
Set Methods
set.union( set2 ) #combines both set values & returns new

lege
set.intersection( set2 ) #combines common values & returns new

Col
pna
A
Let‘s Practice
Store following word meanings in a python dictionary :

ge
table : “a piece of furniture”, “list of facts & figures”
cat : “a small animal”

olle
na C
Ap
You are given a list of subjects for students. Assume one classroom is required for 1
subject. How many classrooms are needed by all students.

”python”, “java”, “C++”, “python”, “javascript”,


“java”, “python”, “java”, “C++”, “C”
Let‘s Practice
WAP to enter marks of 3 subjects from the user and store them in a dictionary. Start with
an empty dictionary & add one by one. Use subject name as key & marks as value.

lege
Col
pna
A
Figure out a way to store 9 & 9.0 as separate values in the set.
(You can take help of built-in data types)

You might also like