GAYATRI VIDYA PARISHAD COLLEGE OF ENGINEERING (Autonomous),
Madhurawada, Visakhapatnam
PYTHON PROGRAMMING LAB FOR
ELECTRICAL ENGINEERING
Experiment-4
WEEK 4: Sets and Dictionaries
Sets:
Sets are used to store multiple items in a single variable. Set items are unordered, unchangeable and do
not allow duplicate values.
Example:
thisset = {"apple", "banana", "cherry", "apple"}
print(thisset)
Output: {'apple', 'banana', 'cherry'}
Set items can be of any data type:
set1 = {"abc", 34, True, 40, "male"}
Sets are defined as objects with the data type 'set'.print(type(set1))
<class 'set'>
Set() Constructor
Set can also be created using the set() constructor
Example: thisset = set(("apple", "banana", "cherry")) # Use double round-brackets
print(thisset)
Output: {'apple', 'banana', 'cherry'}
Accessing items from Sets:
Set items can be accessed using a for loop, it can be checked if a specified value is present in a set, by
using the in keyword.
Example:
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
Output:
apple
banana cherry
Example: print("bananas" in thisset)
Output: False
Change Items
Once a set is created, you cannot change its items, but you can add new items.
Add Items
To add one item to a set use the add() method.
To add items from another set into the current set, use the update() method.
Example:
thisset = {"apple", "banana", "cherry"}
[Link]("orange")
print(thisset)
Output:
{'cherry', 'apple', 'orange', 'banana'}
Remove Item
To remove an item in a set, use the remove(), or the discard() method.
Example:
thisset = {"apple", "banana", "cherry"}
[Link]("orange")
If the item to remove does not exist, remove( ) will raise an error, but discard() will not raise an error.
Example:
thisset = {"apple", "banana", "cherry"}
[Link]("orange")
print(thisset)
pop() method to remove the last item. Since sets are unordered, you will not know what item that gets
removed.
Example:
thisset = {"apple", "banana", "cherry"}
x = [Link]()
print(x)
print(thisset)
Output:
apple
{'banana', 'cherry'}
clear() method empties the set
thisset = {"apple", "banana", "cherry"}
[Link]()
print(thisset)
del keyword will delete the set completely.
Example: thisset = {"apple", "banana", "cherry"}
del(thisset)
4.(a) Write a program that displays which letters are present in both strings.
SOURCE CODE:
s1 = input("Enter string1: ")
s2 = input("Enter string2: ")
common = set(s1).intersection(set(s2))
print(f"Common letters for above strings: {common}")
OUTPUT:
Enter string1: lemon
Enter string2: orange
Common letters for above strings: {'e', 'o', 'n'}
[Link]. Input Expected Actual
Output Output
1 Str1: engineering {'g', 'e'}
Str2: college
2 Str1:MercedesBenz {'s', 'c', 'e'}
Str2: Royce Rolls
Exercises:
1) Both of the strings are converted into sets and the union of both the sets are found using the ‘|’ operator.
Source Code:
str1= input("Enter Your first string: ")
str2=input("Enter Your second string: ")
s=list(set(str1)|set(str2))
print(f"The letter which are present in both strings are: {s}")
2) The letters which are present in the two strings but not in both are found using the ‘^’ operator.
Source Code:
s1 = input("Enter string1: ")
s2 = input("Enter string2: ")
common=list(set(s1)^set(s2))
print(f"The letters which are present in two strings but not both for above strings : {common}")
4.(b) Write a program to sort a given list of strings in the order of their vowel counts.
SOURCE CODE:
vowels = "aeiouAEIOU"
def vowelcount(x):
p = sum([1 for i in x if i in vowels])
return p
inputstrings = input("Enter multiple strings :").split()
print(sorted(inputstrings, key=vowelcount, reverse=True))
OUTPUT:
Enter multiple strings: this is best engineering college
['engineering', 'college', 'this', 'is', 'best']
[Link]. Input Expected Output Actual Output
1 python is an easy ['language', 'programming',
programming language 'easy', 'python', 'is','an']
2 singapore is a beautiful country ['beautiful', 'singapore',
'country', 'is', 'a']
Dictionaries:
What is a Dictionaries?
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is unordered, changeable and does not allow [Link] are
written with curly brackets, and have keys and values:
Example:
Create and print a dictionary:
thisdict = { "brand": "Ford",
"model": "Mustang","year": 1964
}
print(thisdict)
Dictionary Items:
Dictionary items are unordered, changeable, and does not allow duplicates.
Dictionary items are presented in key:value pairs, and can be referred to by using the key name.
Unordered
When we say that dictionaries are unordered, it means that the items does not have a defined order,
you cannot refer to an item by using an index.
Changeable
Dictionaries are changeable, meaning that we can change, add or remove items after thedictionary has
been created.
Duplicates Not Allowed
Dictionaries cannot have two items with the same key:
Example:
Duplicate values will overwrite existing values:
thisdict = { "brand": "Ford",
"model": "Mustang","year": 1964,
"year": 2020
}
print(thisdict)
Dictionary Length:
To determine how many items a dictionary has, use the len() function:
Example:
Print the number of items in the dictionary: print(len(thisdict))
Dictionary Items - Data Types
The values in dictionary items can be of any data type:
Example:
String, int, boolean, and list data types:
thisdict = { "brand": "Ford","electric": False,"year": 1964,
"colors": ["red", "white", "blue"]
}
type()
From Python's perspective, dictionaries are defined as objects with the data type 'dict':
<class 'dict'>
Example:
Print the data type of a dictionary:
thisdict = { "brand": "Ford",
"model": "Mustang","year": 1964
}
print(type(thisdict))
Accessing Items from dictionary:
You can access the items of a dictionary by referring to its key name, inside square brackets:
Example:
Get the value of the "model" key:
thisdict = { "brand": "Ford",
"model": "Mustang","year": 1964
}
x = thisdict["model"]
There is also a method called get() that will give you the same result:
Example:
Get the value of the "model" key:
x = [Link]("model")
Get Keys:
The keys() method will return a list of all the keys in the dictionary.
Example:
Get a list of the keys:
x = [Link]()
The list of the keys is a view of the dictionary, meaning that any changes done to the dictionary will be
reflected in the keys list.
Example:
Add a new item to the original dictionary, and see that the value list gets updated as well:
car = {
"brand": "Ford",
"model": "Mustang","year": 1964
}
x = [Link]()
print(x) #before the change
car["color"] = "white"
print(x) #after the change
Get Values:
The values() method will return a list of all the values in the dictionary.
Example:
Get a list of the values:
x = [Link]()
The list of the values is a view of the dictionary, meaning that any changes done to the
dictionary will be reflected in the values list.
Example:
Add a new item to the original dictionary, and see that the keys list gets updated as well:
car = {
"brand": "Ford",
"model": "Mustang","year": 1964
}
x = [Link]()
print(x) #before the change
car["year"] = 2020
print(x) #after the change
Get Items:
The items() method will return each item in a dictionary, as tuples in a list.
Example:
Get a list of the key:value pairs
x = [Link]()
The returned list is a view of the items of the dictionary, meaning that any changes done to thedictionary
will be reflected in the items list.
Example:
Add a new item to the original dictionary, and see that the items list gets updated as well:
car = {
"brand": "Ford",
"model": "Mustang","year": 1964
}
x = [Link]()
print(x) #before the change
car["year"] = 2020
print(x) #after the change
Check if Key Exists:
To determine if a specified key is present in a dictionary use the in keyword:
Example:
Check if "model" is present in the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang","year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
Change Values:
You can change the value of a specific item by referring to its key name:
Example:
Change the "year" to 2018:thisdict = {
"brand": "Ford",
"model": "Mustang","year": 1964
}
thisdict["year"] = 2018
Update Dictionary:
The update() method will update the dictionary with the items from the given [Link] argument
must be a dictionary, or an iterable object with key:value pairs.
Example:
Update the "year" of the car by using the update() method:
thisdict = { "brand": "Ford",
"model": "Mustang","year": 1964
}
[Link]({"year": 2020})
Adding Items:
Adding an item to the dictionary is done by using a new index key and assigning a value to it:
Example:
thisdict = { "brand": "Ford",
"model": "Mustang","year": 1964
}
thisdict["color"] = "red"
print(thisdict)
Update Dictionary:
The update() method will update the dictionary with the items from a given argument. If theitem does
not exist, the item will be added.
The argument must be a dictionary, or an iterable object with key:value pairs.
Example:
Add a color item to the dictionary by using the update() method:
thisdict = { "brand": "Ford",
"model": "Mustang","year": 1964
}
[Link]({"color": "red"})
Removing Items:
There are several methods to remove items from a dictionary:
Example:
The pop() method removes the item with the specified key name:
thisdict={
"brand": "Ford",
"model": "Mustang","year": 1964
}
[Link]("model")
print(thisdict)
Example:
The popitem() method removes the last inserted item (in versions before 3.7, a random item isremoved
instead):
thisdict = { "brand": "Ford",
"model": "Mustang","year": 1964
}
[Link]()
print(thisdict)
Example:
The delkeyword removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang","year": 1964
}
delthisdict["model"]
print(thisdict)
Example:
The del keyword can also delete the dictionary completely:
thisdict = {
"brand": "Ford",
"model": "Mustang","year": 1964
}
delthisdict
print(thisdict) #this will cause an error because "thisdict" no longer exists.
Example
The clear() method empties the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang","year": 1964
}
[Link]()
print(thisdict)
4.(c) Write a Python script to generate and print a dictionary that contains a number
(between 1 and n) in the form (x, x*x).
SOURCE CODE:
n=int(input("Enter a number: "))
d=dict()
for x in range(1,n+1):
d[x]=x*x
print(d)
OUTPUT:
10
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}
Test Cases:
[Link]. Input ExpectedOutput Actual Output
1. Enter number: 5 1: 1, 2: 4, 3: 9, 4:16, 5:25
2. Enter number: 7 1: 1, 2: 4, 3: 9, 4:16, 5:25, 6:36
4.(d) Write a program to check if a given key exists in a dictionary or not
SOURCE CODE:
d ={1:10,2:20,3:30,4:40,5:50,6:60}
def is_key_present(x):
if x in d:
print('Key is present in the dictionary')
else:
print('Key is not present in the dictionary')
is_key_present(3)
is_key_present(60)
OUTPUT:
Key is present in the dictionary
Key is not present in the dictionary