SlideShare uma empresa Scribd logo
1 de 19
M Vishnuvardhan
Set
Sets are used to store multiple items in a single variable. In Python programming,
a set is created by placing all the items (elements) inside a curly braces { }. set is
a collection which is unordered, unchangeable, unindexed and do not allow
duplicate values.
Eg: fruits = {"apple", "banana", "cherry“}
Set can be empty or can have different types but cannot have duplicates
Eg: names={ }
values={10,”ramu”,35.369,False}
numbers={10,20,30,10,20,30,10,20,30} # but stores only 10 20 30
M Vishnuvardhan
Set – Indexing
Sets are unordered, indexing have no meaning. It not possible to access or change
an element of set using indexing or slicing. Set does not support it
Eg: names = {"apple", "banana", "cherry“}
names[0] # TypeError: 'set' object is not subscriptable
In order to access the elements in the Set generally for loop is used
Eg: for x in names:
print(x)
Since indexing is not supported even slicing operator cannot be used on sets
M Vishnuvardhan
Set – Basic Operations
Python Expression Results Description
len({1, 2, 3}) 3 Length
del {1,2,3} Deleting the set
3 in {1, 2, 3} True Membership
for x in {1, 2, 3}:
print x
2 1 3 Iteration
M Vishnuvardhan
Built-in functions with Set
Function Description
all()
Return True if all elements of the set are true (or
if the list is empty).
any()
Return True if any element of the set is true. If
the list is empty, return False.
enumerate()
Return an enumerate object. It contains the index
and value of all the items of set as a tuple.
len() Return the length (the number of items) in the set.
set()
Convert an iterable (tuple, string, list,
dictionary) to a set.
max() Return the largest item in the set.
min() Return the smallest item in the set
sorted()
Return a new sorted set (does not sort the set
itself).
sum() Return the sum of all elements in the set.
M Vishnuvardhan
Set class methods
Method Description
add() Adds an element to the set
update()
add items from another iterable into the current
set
remove() Removes the specified element
discard() Remove the specified item
pop() Removes an element from the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
M Vishnuvardhan
Set class methods
Method Description
union() Return a set containing the union of sets
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
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)
M Vishnuvardhan
Set class methods
Method Description
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
symmetric_difference()
Returns a set with the symmetric
differences of two sets
symmetric_difference_update()
inserts the symmetric differences
from this set and another
M Vishnuvardhan
Frozen Sets
Frozenset is the same as set except the frozensets are immutable which means
that elements from the frozenset cannot be added or removed once created.
frozenset() function is used to create an unchangeable frozenset object (which is
like a set object, only unchangeable).
Syntax: frozenset(iterable) ( Iterable can be list, set, tuple etc.)
Eg: mylist = ['apple', 'banana', 'cherry’]
x = frozenset(mylist)
x[1] = "strawberry"
TypeError: 'frozenset' object does not support item assignment
M Vishnuvardhan
Frozen Sets
Frozenset supports methods like copy(), difference(), intersection(), isdisjoint(),
issubset(), issuperset(), symmetric_difference() and union().
Being immutable it does not have method that add or remove elements.
Eg: A = frozenset([1, 2, 3, 4])
B = frozenset([3, 4, 5, 6])
A.isdisjoint(B) # Output: False
A.difference(B) # Output: frozenset({1, 2})
A | B # Output: frozenset({1, 2, 3, 4, 5, 6})
A.add(3) # AttributeError: 'frozenset' object has no
attribute 'add'
M Vishnuvardhan
Dictionary
Dictionaries are used to store data values in key: value pairs. A dictionary
is a collection which is ordered (From Python version 3.7, they are ordered
earlier, they are unordered.) changeable and do not allow duplicates
Keys are unique within a dictionary while values may not be. The values of
a dictionary can be of any type, but the keys must be of an immutable data
type such as strings, numbers, or tuples.
Eg:stu = { "Name": "Ramu","RollNo": 1234, "Marks": 576 }
stu = { "Name": "Ramu","RollNo": 1234, “Name": ”Raju”}
M Vishnuvardhan
Properties
» Duplicate keys are not allowed but values can have duplicates.
Eg: dict = {'Name’: ‘Ramu', 'Age': 7, 'Name’: ‘Ravi’}
» Keys must be immutable. i.e., strings, numbers or tuples are allowed as
dictionary keys but lists are not allowed.
Eg: dict = {['Name']: ‘Ramu’, 'Age': 7}
# TypeError: unhashable type: 'list'
M Vishnuvardhan
Indexing
In order to access dictionary elements dictionary name followed by square
brackets along with the key name to obtain its value.
Syntax: dictionaryName [ “keyName”] # returns the value
associated with the keyName
Eg: details = {'Name’: ‘Ramu’, 'Age': 5, 'Class': 'First’}
print (details['Name']) # Output: Ramu
print ( details['Age']) # Output: 5
print(details['Class']) # Output: First
print(details[‘dob’]) # Throws KeyError: 'dob'
M Vishnuvardhan
Updating
Python allows to update the value of a specific item by referring to its key
name. It allows to add a new key-value pair, modifying an existing entry, or
deleting an existing entry.
Eg: details={"Name":“Ramu","Age":5,"Class":"First"}
details[“age”]=4 # update value
details[“city”] = “Anantapur” # add a new key: value pair
del details[“city”] # deletes key named city
del details # deletes dictionary
M Vishnuvardhan
Built-in Functions
Python provides Built-in functions those can be used with Dictionary to
perform different tasks
Function Description
len(dict)
Returns length of the dictionary. This would be equal to the
number of items in the dictionary.
str(dict) Produces a printable string representation of a dictionary
type(variable)
Returns the type of the passed variable. i.e., the object type
is returned
M Vishnuvardhan
Dictionary Class Methods
Python provides multiple methods in Dictionary class which can be used to
manipulate dictionaries.
Method Description
update()
Updates the dictionary with the specified key-value pairs also
used to add new key: value pair
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
clear() Removes all the elements from the dictionary
get() Returns the value of the specified key
M Vishnuvardhan
Dictionary Class Methods
Method Description
keys() Returns a list containing the dictionary's keys
values() Returns a list of all the values in the dictionary
copy() Returns a copy of the dictionary
fromkeys() returns the dictionary with key mapped to a specific value
items() Returns a list containing a tuple for each key value pair
setdefault() Returns the value of the specified key. If the key does not
exist: insert the key, with the specified value
M Vishnuvardhan
Using for loop
When looping through a dictionary, the return value are the keys of the
dictionary, but there are methods to return the values as well.
Eg: stu={"name":"ramu","age":25,"class":"mpcs","medium":"english"}
#get values
for x in stu:
print(stu[x])
#get values
for x in stu.values():
print(x)
#get keys
for x in stu.keys():
print(x)
OR
OR
#get keys
for x in stu:
print(x)
#getting both keys and values
for x,y in stu.items():
print(x,y)
M Vishnuvardhan

Mais conteúdo relacionado

Mais procurados

Decision Tree - ID3
Decision Tree - ID3Decision Tree - ID3
Decision Tree - ID3
Xueping Peng
 

Mais procurados (20)

Machine Learning with Decision trees
Machine Learning with Decision treesMachine Learning with Decision trees
Machine Learning with Decision trees
 
K-Means Clustering Algorithm - Cluster Analysis | Machine Learning Algorithm ...
K-Means Clustering Algorithm - Cluster Analysis | Machine Learning Algorithm ...K-Means Clustering Algorithm - Cluster Analysis | Machine Learning Algorithm ...
K-Means Clustering Algorithm - Cluster Analysis | Machine Learning Algorithm ...
 
Feature Selection in Machine Learning
Feature Selection in Machine LearningFeature Selection in Machine Learning
Feature Selection in Machine Learning
 
Mining Frequent Patterns And Association Rules
Mining Frequent Patterns And Association RulesMining Frequent Patterns And Association Rules
Mining Frequent Patterns And Association Rules
 
Lecture 4 Decision Trees (2): Entropy, Information Gain, Gain Ratio
Lecture 4 Decision Trees (2): Entropy, Information Gain, Gain RatioLecture 4 Decision Trees (2): Entropy, Information Gain, Gain Ratio
Lecture 4 Decision Trees (2): Entropy, Information Gain, Gain Ratio
 
K means clustering
K means clusteringK means clustering
K means clustering
 
backpropagation in neural networks
backpropagation in neural networksbackpropagation in neural networks
backpropagation in neural networks
 
Association rule mining and Apriori algorithm
Association rule mining and Apriori algorithmAssociation rule mining and Apriori algorithm
Association rule mining and Apriori algorithm
 
Understanding Bagging and Boosting
Understanding Bagging and BoostingUnderstanding Bagging and Boosting
Understanding Bagging and Boosting
 
Presentation on supervised learning
Presentation on supervised learningPresentation on supervised learning
Presentation on supervised learning
 
Regularization in deep learning
Regularization in deep learningRegularization in deep learning
Regularization in deep learning
 
Introduction to CNN
Introduction to CNNIntroduction to CNN
Introduction to CNN
 
Decision tree
Decision treeDecision tree
Decision tree
 
Decision trees in Machine Learning
Decision trees in Machine Learning Decision trees in Machine Learning
Decision trees in Machine Learning
 
DBSCAN : A Clustering Algorithm
DBSCAN : A Clustering AlgorithmDBSCAN : A Clustering Algorithm
DBSCAN : A Clustering Algorithm
 
Decision Tree - ID3
Decision Tree - ID3Decision Tree - ID3
Decision Tree - ID3
 
Decision tree
Decision treeDecision tree
Decision tree
 
Feature selection
Feature selectionFeature selection
Feature selection
 
Gradient descent method
Gradient descent methodGradient descent method
Gradient descent method
 
K means Clustering Algorithm
K means Clustering AlgorithmK means Clustering Algorithm
K means Clustering Algorithm
 

Semelhante a Python Sets_Dictionary.pptx

11 Introduction to lists.pptx
11 Introduction to lists.pptx11 Introduction to lists.pptx
11 Introduction to lists.pptx
ssuser8e50d8
 
beginners_python_cheat_sheet_pcc_all (1).pdf
beginners_python_cheat_sheet_pcc_all (1).pdfbeginners_python_cheat_sheet_pcc_all (1).pdf
beginners_python_cheat_sheet_pcc_all (1).pdf
ElNew2
 

Semelhante a Python Sets_Dictionary.pptx (20)

Lists_tuples.pptx
Lists_tuples.pptxLists_tuples.pptx
Lists_tuples.pptx
 
Dictionaries and Sets in Python
Dictionaries and Sets in PythonDictionaries and Sets in Python
Dictionaries and Sets in Python
 
Basic data structures in python
Basic data structures in pythonBasic data structures in python
Basic data structures in python
 
The Datatypes Concept in Core Python.pptx
The Datatypes Concept in Core Python.pptxThe Datatypes Concept in Core Python.pptx
The Datatypes Concept in Core Python.pptx
 
Revision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.docRevision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.doc
 
Dictionaries and Sets in Python
Dictionaries and Sets in PythonDictionaries and Sets in Python
Dictionaries and Sets in Python
 
Pytho_tuples
Pytho_tuplesPytho_tuples
Pytho_tuples
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
 
List in Python
List in PythonList in Python
List in Python
 
Python Data Types.pdf
Python Data Types.pdfPython Data Types.pdf
Python Data Types.pdf
 
Python Data Types (1).pdf
Python Data Types (1).pdfPython Data Types (1).pdf
Python Data Types (1).pdf
 
Python dictionary
Python   dictionaryPython   dictionary
Python dictionary
 
Set methods in python
Set methods in pythonSet methods in python
Set methods in python
 
Python list
Python listPython list
Python list
 
11 Introduction to lists.pptx
11 Introduction to lists.pptx11 Introduction to lists.pptx
11 Introduction to lists.pptx
 
2. Python Cheat Sheet.pdf
2. Python Cheat Sheet.pdf2. Python Cheat Sheet.pdf
2. Python Cheat Sheet.pdf
 
python cheat sheat, Data science, Machine learning
python cheat sheat, Data science, Machine learningpython cheat sheat, Data science, Machine learning
python cheat sheat, Data science, Machine learning
 
Beginner's Python Cheat Sheet
Beginner's Python Cheat SheetBeginner's Python Cheat Sheet
Beginner's Python Cheat Sheet
 
beginners_python_cheat_sheet_pcc_all (1).pdf
beginners_python_cheat_sheet_pcc_all (1).pdfbeginners_python_cheat_sheet_pcc_all (1).pdf
beginners_python_cheat_sheet_pcc_all (1).pdf
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptx
 

Mais de M Vishnuvardhan Reddy

Mais de M Vishnuvardhan Reddy (20)

Python Control Structures.pptx
Python Control Structures.pptxPython Control Structures.pptx
Python Control Structures.pptx
 
Python Strings.pptx
Python Strings.pptxPython Strings.pptx
Python Strings.pptx
 
Python Basics.pptx
Python Basics.pptxPython Basics.pptx
Python Basics.pptx
 
Python Operators.pptx
Python Operators.pptxPython Operators.pptx
Python Operators.pptx
 
Python Datatypes.pptx
Python Datatypes.pptxPython Datatypes.pptx
Python Datatypes.pptx
 
DataScience.pptx
DataScience.pptxDataScience.pptx
DataScience.pptx
 
Html forms
Html formsHtml forms
Html forms
 
Cascading Style Sheets
Cascading Style SheetsCascading Style Sheets
Cascading Style Sheets
 
Java Threads
Java ThreadsJava Threads
Java Threads
 
Java Streams
Java StreamsJava Streams
Java Streams
 
Scanner class
Scanner classScanner class
Scanner class
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Java intro
Java introJava intro
Java intro
 
Java applets
Java appletsJava applets
Java applets
 
Exception handling
Exception handling Exception handling
Exception handling
 
Control structures
Control structuresControl structures
Control structures
 
Constructors
ConstructorsConstructors
Constructors
 
Classes&objects
Classes&objectsClasses&objects
Classes&objects
 
Shell sort
Shell sortShell sort
Shell sort
 
Selection sort
Selection sortSelection sort
Selection sort
 

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Último (20)

TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 

Python Sets_Dictionary.pptx

  • 1.
  • 2. M Vishnuvardhan Set Sets are used to store multiple items in a single variable. In Python programming, a set is created by placing all the items (elements) inside a curly braces { }. set is a collection which is unordered, unchangeable, unindexed and do not allow duplicate values. Eg: fruits = {"apple", "banana", "cherry“} Set can be empty or can have different types but cannot have duplicates Eg: names={ } values={10,”ramu”,35.369,False} numbers={10,20,30,10,20,30,10,20,30} # but stores only 10 20 30
  • 3. M Vishnuvardhan Set – Indexing Sets are unordered, indexing have no meaning. It not possible to access or change an element of set using indexing or slicing. Set does not support it Eg: names = {"apple", "banana", "cherry“} names[0] # TypeError: 'set' object is not subscriptable In order to access the elements in the Set generally for loop is used Eg: for x in names: print(x) Since indexing is not supported even slicing operator cannot be used on sets
  • 4. M Vishnuvardhan Set – Basic Operations Python Expression Results Description len({1, 2, 3}) 3 Length del {1,2,3} Deleting the set 3 in {1, 2, 3} True Membership for x in {1, 2, 3}: print x 2 1 3 Iteration
  • 5. M Vishnuvardhan Built-in functions with Set Function Description all() Return True if all elements of the set are true (or if the list is empty). any() Return True if any element of the set is true. If the list is empty, return False. enumerate() Return an enumerate object. It contains the index and value of all the items of set as a tuple. len() Return the length (the number of items) in the set. set() Convert an iterable (tuple, string, list, dictionary) to a set. max() Return the largest item in the set. min() Return the smallest item in the set sorted() Return a new sorted set (does not sort the set itself). sum() Return the sum of all elements in the set.
  • 6. M Vishnuvardhan Set class methods Method Description add() Adds an element to the set update() add items from another iterable into the current set remove() Removes the specified element discard() Remove the specified item pop() Removes an element from the set clear() Removes all the elements from the set copy() Returns a copy of the set
  • 7. M Vishnuvardhan Set class methods Method Description union() Return a set containing the union of sets 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 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)
  • 8. M Vishnuvardhan Set class methods Method Description 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 symmetric_difference() Returns a set with the symmetric differences of two sets symmetric_difference_update() inserts the symmetric differences from this set and another
  • 9. M Vishnuvardhan Frozen Sets Frozenset is the same as set except the frozensets are immutable which means that elements from the frozenset cannot be added or removed once created. frozenset() function is used to create an unchangeable frozenset object (which is like a set object, only unchangeable). Syntax: frozenset(iterable) ( Iterable can be list, set, tuple etc.) Eg: mylist = ['apple', 'banana', 'cherry’] x = frozenset(mylist) x[1] = "strawberry" TypeError: 'frozenset' object does not support item assignment
  • 10. M Vishnuvardhan Frozen Sets Frozenset supports methods like copy(), difference(), intersection(), isdisjoint(), issubset(), issuperset(), symmetric_difference() and union(). Being immutable it does not have method that add or remove elements. Eg: A = frozenset([1, 2, 3, 4]) B = frozenset([3, 4, 5, 6]) A.isdisjoint(B) # Output: False A.difference(B) # Output: frozenset({1, 2}) A | B # Output: frozenset({1, 2, 3, 4, 5, 6}) A.add(3) # AttributeError: 'frozenset' object has no attribute 'add'
  • 11. M Vishnuvardhan Dictionary Dictionaries are used to store data values in key: value pairs. A dictionary is a collection which is ordered (From Python version 3.7, they are ordered earlier, they are unordered.) changeable and do not allow duplicates Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples. Eg:stu = { "Name": "Ramu","RollNo": 1234, "Marks": 576 } stu = { "Name": "Ramu","RollNo": 1234, “Name": ”Raju”}
  • 12. M Vishnuvardhan Properties » Duplicate keys are not allowed but values can have duplicates. Eg: dict = {'Name’: ‘Ramu', 'Age': 7, 'Name’: ‘Ravi’} » Keys must be immutable. i.e., strings, numbers or tuples are allowed as dictionary keys but lists are not allowed. Eg: dict = {['Name']: ‘Ramu’, 'Age': 7} # TypeError: unhashable type: 'list'
  • 13. M Vishnuvardhan Indexing In order to access dictionary elements dictionary name followed by square brackets along with the key name to obtain its value. Syntax: dictionaryName [ “keyName”] # returns the value associated with the keyName Eg: details = {'Name’: ‘Ramu’, 'Age': 5, 'Class': 'First’} print (details['Name']) # Output: Ramu print ( details['Age']) # Output: 5 print(details['Class']) # Output: First print(details[‘dob’]) # Throws KeyError: 'dob'
  • 14. M Vishnuvardhan Updating Python allows to update the value of a specific item by referring to its key name. It allows to add a new key-value pair, modifying an existing entry, or deleting an existing entry. Eg: details={"Name":“Ramu","Age":5,"Class":"First"} details[“age”]=4 # update value details[“city”] = “Anantapur” # add a new key: value pair del details[“city”] # deletes key named city del details # deletes dictionary
  • 15. M Vishnuvardhan Built-in Functions Python provides Built-in functions those can be used with Dictionary to perform different tasks Function Description len(dict) Returns length of the dictionary. This would be equal to the number of items in the dictionary. str(dict) Produces a printable string representation of a dictionary type(variable) Returns the type of the passed variable. i.e., the object type is returned
  • 16. M Vishnuvardhan Dictionary Class Methods Python provides multiple methods in Dictionary class which can be used to manipulate dictionaries. Method Description update() Updates the dictionary with the specified key-value pairs also used to add new key: value pair pop() Removes the element with the specified key popitem() Removes the last inserted key-value pair clear() Removes all the elements from the dictionary get() Returns the value of the specified key
  • 17. M Vishnuvardhan Dictionary Class Methods Method Description keys() Returns a list containing the dictionary's keys values() Returns a list of all the values in the dictionary copy() Returns a copy of the dictionary fromkeys() returns the dictionary with key mapped to a specific value items() Returns a list containing a tuple for each key value pair setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with the specified value
  • 18. M Vishnuvardhan Using for loop When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well. Eg: stu={"name":"ramu","age":25,"class":"mpcs","medium":"english"} #get values for x in stu: print(stu[x]) #get values for x in stu.values(): print(x) #get keys for x in stu.keys(): print(x) OR OR #get keys for x in stu: print(x) #getting both keys and values for x,y in stu.items(): print(x,y)