Skip to content

Set and Dictionary

SET
The set data structure of Python is a list of data elements stored in unordered or no index manner. Set is created using pair of curly braces.

🐍
filename.py
#Example code to create a Set
fruits = {"apple", "banana", "cherry"}
print(fruits)

Access Items:
Since set is not maintain any index, we cannot access elements of set using index values. But we can search for the presence of a data element by its value.

🐍
filename.py
#Check if "banana" is present in the set:
fruits = {"apple", "banana", "cherry"}
print("banana" in fruits)

Add Items:
We cannot update or change the existing values of a set but can add new data elements. The place of the newly inserted data element cannot be determined since set is unordered.

Β 

The following ways can be used to add new data items to Set:
1. Using add() function: to add a single data element
2. Using update() function: to add more than one data items

🐍
filename.py
#Example to add an item to a set, using the add() method
fruits = {"apple", "banana", "cherry"}
fruits.add("orange")
print(fruits)

#Example to add multiple items to a set, using the update() method
fruits = {"apple", "banana", "cherry"}
fruits.update(["orange", "mango", "grapes"])
print(fruits)

The len() method can be used with Set to know the number of set elements.

🐍
filename.py
#Example to get the number of items in a set
fruits = {"apple", "banana", "cherry"}
print(len(fruits))

Remove Item:
The existing data items of Set can be removed by the following methods:
1. Using remove() method: raises an error if the items removable is not exists
2. Using discard() method: don’t raise any error if the removable item is not present
3. Using pop() method: always remove the last element but cannot say which item will get removed since set is unordered. This method also returns the removed item.
4. Using clear() method: empty the set
5. Using del keyword: removes set from memory

🐍
filename.py
#Example code to remove "banana" by using the remove() method
fruits = {"apple", "banana", "cherry"}
fruits.remove("banana")
print(fruits)

#Example code to remove "banana" by using the discard() method
fruits = {"apple", "banana", "cherry"}
fruits.discard("banana")
print(fruits)

#Example code to remove the last item by using the pop() method
fruits = {"apple", "banana", "cherry"}
x = fruits.pop()
print(x)
print(fruits)

#Example code to use clear() method to empty the set
fruits = {"apple", "banana", "cherry"}
fruits.clear()
print(fruits)

#Example code to use del keyword will delete the set completely
fruits = {"apple", "banana", "cherry"}
del fruits
print(fruits)

Join Two Sets:
Joining of sets means creating a new set containing all the elements of given sets or add elements of one set to another. In any case, the resultant set won’t have any duplicate values. Two or more sets can be joined using the following way:
1. Using union() method: creates a new set by containing all items from joining sets
2. Using update() method: adds elements of one set to another.

🐍
filename.py
#Example code to use union() method returns a new set with all items from both sets
set1 = {"a", "b", "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)

#Example code to use update() method inserts the items in set2 into set1
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set1.update(set2)
print(set1)

DICTIONARIES:
Dictionary is also a collection of unordered data structure. Dictionary can be created using key and value pairs inside pair of curly braces. Each key and value pair is separated by colon(:) and each item of dictionary is separated with comma (,).

Β 

Keys of dictionary must be unique but values may not be. Dictionary can contain any type of values but keys must be immutable type like strings, numbers or tuples.

🐍
filename.py
#Example code to create and print a dictionary
mydict ={
  "brand": "Renault",
  "model": "Climber",
  "year": 2019
}
print(mydict)

Accessing Values in Dictionary:
Elements of the dictionary can be accessed using their keys inside square brackets. The in-built get() method can also be used for this.

🐍
filename.py
#Example code
dict1 = {'Name': 'Shiva', 'Age': 18, 'Class': 'First'}
print ("dict1['Name']: ", dict1['Name'])
print ("dict1['Age']: ", dict1['Age'])
print(dict1.get('Name'))

Updating Dictionary:
Updating of dictionary involves adding a new key-value pair or modifying an existing item or deleting an item.

🐍
filename.py
#Example code
Dict1 = {'Name': 'Ram', 'Age': 22, 'Class': 'First'}
Dict1['Age'] = 28; # update existing entry
Dict1['College'] = "Govt Degree College"; # Add new entry
print ("Dict1['Age']: ", Dict1['Age'])
print ("Dict1['College']: ", Dict1['College'])

Delete Dictionary Elements:
Removal of elements of dictionary can be done by the following ways:
1. Using del keyword
2. Using clear() method

🐍
filename.py
#Example code
dct = {'Name': 'Krishna', 'Age': 7, 'Class': 'First'}
del dct['Name']; # remove entry with key 'Name'
print(dct)
dct.clear();     # remove all entries in dict
print ("dct['Age']: ", dct['Age'])
del dct ;        # delete entire dictionary
print ("dct['Class']: ", dct['Class'])