Creating dictionary of sets in Python
In this article, we will discuss how to create a dictionary of sets in Python.
Method 1: Naive Approach
We can create a dictionary of sets by passing sets as values to the keys.
Syntax:
{ ‘Key’: Set 1, ‘Key’:Set 2,…………..,’Key’: Set n}
Example: Python program to create a dictionary of sets for student details
Python3
# create dictionary of sets for student detailsdata = {'Student Roll-no': {1, 2, 3, 4, 5}, 'Student Aadhar No': {11, 22, 33, 44, 55}} # displayprint(data) |
Output:
{‘Student Roll-no’: {1, 2, 3, 4, 5}, ‘Student Aadhar No’: {33, 11, 44, 22, 55}}
As per definition, a set will not allow duplicates.
Example 2: Python program to show that it will not allow duplicates
Python3
# create dictionary of sets for student detailsdata = {'Student Roll-no': {1, 2, 3, 4, 5, 1, 2, 3, 2}, 'Student Aadhar No': {11, 22, 33, 44, 55, 22, 33, 44, 11}} # displayprint(data) |
Output:
{‘Student Roll-no’: {1, 2, 3, 4, 5}, ‘Student Aadhar No’: {33, 11, 44, 22, 55}}
Method 2: Using defaultdict method
Here, in this approach, we are going to create a default set and then pass the key values to it.
Syntax:
defaultdict(set)
Syntax to pass the dictionary with key and value:
dictinary_name[“key”] |= {‘value1’, ‘value2′, ……………,’value n’}
where,
- dictionary_name is the input dictionary
- key is the key
- values are the set
Example: Python code to create a dictionary of sets of student data
Python3
# import defaultdict modulefrom collections import defaultdict # create an empty set of dictionarydictionary = defaultdict(set) # enter key value pair 1dictionary["Student Roll-no"] |= {1, 2, 3, 4, 5} # ennter key value pair 2dictionary["Student Aadhar No"] |= {11, 22, 33, 44, 55} # displaydictionary |
Output:
defaultdict(set,
{‘Student Aadhar No’: {11, 22, 33, 44, 55},
‘Student Roll-no’: {1, 2, 3, 4, 5}})
Method 3: Using setdefault() method
The setdefault() method returns the value of a key in the dictionary. If not, it inserts a key with a value to the dictionary.
Syntax:
dict.setdefault(key, default_value)
where,
- key – Key to being searched in the dictionary.
- default_value is the value of a particular key
Example: Python program to insert student names set into the dictionary
Python3
# Dictionary with student datadata = {'Student No': {1, 2, 3, 4, 5}, 'Student Aadhar No': {11, 22, 33, 44, 55}} # using setdefault() method to get aadhar number# of the studentsprint(data.setdefault('Student Aadhar No')) # using setdefault() method to get aadhar number# of the studentsprint(data.setdefault('Student No')) # set the third set using setdefault method for # student namesdata = data.setdefault( 'Student Names', {'sravan', 'gopi', 'ramya', 'durga', 'sudheer'}) # displaydata |
Output:
{33, 11, 44, 22, 55}
{1, 2, 3, 4, 5}
{‘durga’, ‘gopi’, ‘ramya’, ‘sravan’, ‘sudheer’}



