Python Notes 11 Dictionary Tuples and Sets 1664121924
Python Notes 11 Dictionary Tuples and Sets 1664121924
Tuples
● A tuple is an ordered collection of elements/entries.
● Objects in a Tuple are immutable i.e. they cannot be altered once created.
● In a tuple, elements are placed within parentheses, separated by commas.
● The elements in a tuple can be of different data types like integer, list, etc.
>>> a=(1,2)
>>> b=("eat","dinner","man","boy")
>>> print(a)
(1,2)
>>> print(type(a))
<class 'tuple'>
1
Fahad sayyed – notes 11
Linked in @ fahad sayyed
>>> c= 1,2,3,4,5
>>> print(c)
(1,2,3,4,5)
>>> print(type(c))
<class 'tuple'>
Note: If we assign a set of comma separated elements (or objects) to a set of comma
separated variables, then these variables are assigned the corresponding values. For
Example:
>>> e, f= "boy","man"
>>> print(e)
boy
>>> print(f)
man
a=()
b=()
#Here 'a' and 'b' are empty tuples.
>>> a=("Hamburger")
>>> print(type(a))
<class 'str'>
● If you try to create a tuple using the keyword tuple, you will get:
>>> tuple("Hamburger")
('H', 'a', 'm', 'b', 'u', 'r', 'g', 'e', 'r')
2
Fahad sayyed – notes 11
Linked in @ fahad sayyed
● To create such a tuple, along with a single element inside parentheses, we need a
trailing comma. This would tell the system that it is in fact, a tuple.
>>> a=("Hamburger",)
>>> print(type(a))
<class 'tuple>
#Here a is indeed a tuple. Thus, the trailing comma is important in such an
assignment.
Tuple List
Indexing in a Tuple
● Indexing in a Tuple starts from index 0.
● The highest index is the NumberOfElementsInTheTuple-1.
● So a tuple having 10 elements would have indexing from 0-9.
● This system is just like the one followed in Lists.
Negative Indexing
● Python language allows negative indexing for its tuple elements.
● The last element in the tuple has an index -1, the second last element has index -2,
and so on.
3
Fahad sayyed – notes 11
Linked in @ fahad sayyed
Element 1 15 13 18 19 23 4 5 2 3
Index 0 1 2 3 4 5 6 7 8 9
Negative -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
indexing
>>> print(myTemp[0])
1
>>> print(myTemp[8])
2
>>> print(myTemp[-1])
3
If any index out of this range is tried to be accessed, then it would give the following error.
>>> print(myTemp[10])
IndexError: tuple index out of range
>>> print(myTemp[20])
IndexError: tuple index out of range
>>> print(myTemp[-100])
IndexError: tuple index out of range
Slicing of a Tuple
● We can slice a Tuple and then access any required range of elements. Slicing is done
by the means of a slicing operator which is “:”.
● The basic format of slicing is:
>>> print(myTemp[1:4])
(15,13,18)
>>> print(myTemp[7:])
(5,2,3)
4
Fahad sayyed – notes 11
Linked in @ fahad sayyed
● Though, you can change items from any mutable object in the tuple.
>>> del(myTemp)
>>> print(myTemp)
NameError: name 'myTemp' is not defined
# The name error shows that the tuple 'myTemp' has been deleted
5
Fahad sayyed – notes 11
Linked in @ fahad sayyed
Tuples Functions
● We can use loops to iterate through a tuple: For example, if we want to print all
the elements in the tuple. We can run the following loop.
myTemp=(1,2,3)
for t in myTemp:
print(t)
Output:
1
2
3
● Checking whether the tuple contains a particular element: The keyword used is
in. We can easily get a boolean output using this keyword. It returns True if the
tuple contains the given element, else the output is False.
>>> 10 in myTemp
False
>>> 4 in myTemp
True
● Finding the length of a tuple: We can easily find the number of elements that any
tuple contains. The keyword used is len.
>>> print(len(myTemp))
6
● Concatenation: We can add elements from two different tuples and form a single
tuple out of them. This process is concatenation and is similar to data types like
string and list. We can use the “ + ” operator to combine two tuples.
a = (1,2,3,4)
b = (5,6,7,8)
d = a+b
print(d)
Out[]: (1,2,3,4,5,6,7,8)
6
Fahad sayyed – notes 11
Linked in @ fahad sayyed
We can also combine two tuples into another tuple in order to form a nested tuple. This is
done as follows:
a = (1,2,3,4)
b = (5,6,7,8)
d = (a, b)
print(d)
--> ((1,2,3,4),(5,6,7,8))
# Here d is a nested tuple which is formed from 2 different tuples.
● Repetition of a Tuple: We can repeat the elements from a given tuple into a
different tuple. The operator used is “ * ”, the multiplication operator. In other
words, by using this operator, we can repeat the elements of a tuple as many times
as we want.
>>> a = (1,2,3,4)
>>> print(a*4)
(1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4)
# The same tuple elements are repeated 4 times in the form of another
tuple.
>>> a = (1,2,3,4)
>>> print(min(a))
1
>>> print(max(a))
4
Note: We can find the minimum and maximum of only those tuples, which have
comparable entries. We cannot compare two different data types like a string and a tuple.
Such comparisons would throw an error.
For example:
>>> s= (1,2,"string",4)
>>> print(min(s))
TypeError: '<' not supported between instances of 'string' and 'int'
7
Fahad sayyed – notes 11
Linked in @ fahad sayyed
>>> e= (1,2,2.6,4)
>>> print(min(e))
1
# Even though the data types are different , however since a float can be
compared to a floating point value, hence this operation does not give an
error.
● Converting a list to a tuple: We can typecast a list into a tuple. The keyword used is
tuple. This is done as follows:
1
2
(3,4,5,5)
8
Fahad sayyed – notes 11
Linked in @ fahad sayyed
9
Fahad sayyed – notes 11
Linked in @ fahad sayyed
Dictionaries
● A Dictionary is a Python’s implementation of a data structure that is more generally
known as an associative array.
● A dictionary is an unordered collection of key-value pairs.
● Indexing in a dictionary is done using these “keys”.
● Each pair maps the key to its value.
● Literals of the type dictionary are enclosed within curly brackets.
● Within these brackets, each entry is written as a key followed by a colon ” : ”, which is
further followed by a value. This is the value that corresponds to the given key.
● These keys must be unique and cannot be any immutable data type. Eg- string,
integer, tuples, etc. They are always mutable.
● The values need not be unique. They can be repetitive and can be of any data type
(Both mutable and immutable)
● Dictionaries are mutable, which means that the key-value pairs can be changed.
myDictionary = {
<key>: <value>,
<key>: <value>,
.
.
<key>: <value>
}
10
Fahad sayyed – notes 11
Linked in @ fahad sayyed
Creating A Dictionary
11
Fahad sayyed – notes 11
Linked in @ fahad sayyed
This method is particularly useful if we want to create a dictionary with variable keys and all
the keys must have the same value. The values corresponding to all the keys is exactly the
same. This is done as follows:
# We can initialise all the values to a custom value too. This is done by
providing the second argument as the desired value.
>>> d2= dict.fromkeys(["abc",1,"two"],6)
>>> print(d2)
["abc":6 ,1:6, "two":6]
Similar to the list and tuples, this can be done by the square bracket operator [ ].
foo= {"a":1,"b":2,"c":3}
print(foo["a"])
--> 1
print(foo["c"])
--> 3
12
Fahad sayyed – notes 11
Linked in @ fahad sayyed
If we want the value corresponding to any key , we can even use an inbuilt dictionary
method called get.
A very unique feature about this method is that , incase the desired key is not present in
the dictionary , it won’t throw an error or an exception. It would simple return None.
We can make use of this feature in another way. Say we want the method to do the
following action: If the key is present in the dictionary then return the value corresponding
to the key. In case the key is not present, return a custom desired value ( say 0 ).
13
Fahad sayyed – notes 11
Linked in @ fahad sayyed
This can be done using the method .items(). This method returns all the different items
(key-value pairs) present in the dictionary in the form of a list of tuples, with the first
element of the tuple as the key and the second element as the value corresponding to this
key .
bar= {2:1,3:2,4:3}
for t in bar:
print(t)
Out[]:
2
3
4
# Here t is the key in the dictionary and hence when we print t in all
iterations then all the keys are printed.
14
Fahad sayyed – notes 11
Linked in @ fahad sayyed
for t in bar:
print(t, bar[t])
Out[]:
2 1
3 2
4 3
# Here along with the keys, the values which are bar[t] are printed. In
this loop, the values are accessed using the keys.
If we want to update the value of an already existing key in the dictionary then we can
simply assign the new value to the given key. This is done as follows:
Now if we want to add a new key-value pair to our dictionary, then we can make a similar
assignment. If we have to add a key-value pair as "man":"boy", then we can make the
assignment as:
>>> bar["man"]="boy"
>>> print(bar)
{2:1,3:2,4:3,"man":"boy"}
15
Fahad sayyed – notes 11
Linked in @ fahad sayyed
a= {1:2,2:3,3:4}
b= {7:2,10:3,6:4}
a.update(b)
print(a)
--> {1:2,2:3,3:4,7:2,10:3,6:4}
In this process, the second dictionary is unchanged and the contents of the second
dictionary are copied into the first dictionary. The uncommon keys from the second
dictionary are added to the first with their corresponding values. However, if these
dictionaries have any common key, then the value of the common key present in the first
dictionary is updated to the new value from the second.
Deleting an entry:
In order to delete an entry corresponding to any key in a dictionary , we can simple pop the
key from the dictionary. The method used here is .pop() . This method removes the
key-value pair corresponding to any particular key and then returns the value of the
removed key-value pair.
>>> c={1:2,2:(3,23,3),3:4}
>>> c.pop(2)
(3,23,3)
>>> c={1:2,2:(3,23,3),3:4}
>>> c.clear()
>>> print(c)
{}
16
Fahad sayyed – notes 11
Linked in @ fahad sayyed
To convert the string to a list, we use the .split() function. This gives us a list of words.
Now, we run a loop through this list and keep making changes to the frequency in the
dictionary. If the word in the current iteration already exists in the dictionary as a key, then
we simply increase the value(or frequency) by 1. If the key does not exist, we create a new
key-value pair with value as 1.
Now we have a dictionary with unique keys and their respective frequencies. Now we run
another loop to print the keys with the frequency 'k'.
17
Fahad sayyed – notes 11
Linked in @ fahad sayyed
Sets
Mathematically a set is a collection of items (not in any particular order). A Python set is
similar to this mathematical definition with below additional conditions.
● The elements in a set cannot be repeated i.e. an element can occur only once.
● The elements in the set are immutable(cannot be modified) but the set as a whole is
mutable.
● There is no index attached to any element in a python set. So they do not support
any indexing or slicing operation.
Set Operations
The sets in python are typically used for mathematical operations like union, intersection,
difference, and complement, etc. We can create a set, access its elements, and carry out
these mathematical operations as shown below.
Creating a set
A set is created by using the set() function or placing all the elements within a pair of curly
braces, separated by commas.
Days=set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"])
Months={"Jan","Feb","Mar"}
Dates={21,22,17}
print(Days)
print(Months)
print(Dates)
18
Fahad sayyed – notes 11
Linked in @ fahad sayyed
Days=set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"])
for d in Days:
print(d)
Wed
Sun
Fri
Tue
Mon
Thu
Sat
>>> Days=set(["Mon","Tue","Wed","Thu","Fri","Sat"])
>>> Days.add("Sun")
>>> print(Days)
set(['Wed', 'Sun', 'Fri', 'Tue', 'Mon', 'Thu', 'Sat'])
>>> Days=set(["Mon","Tue","Wed","Thu","Fri","Sat"])
>>> Days.discard("Sun")
>>> print(Days)
set(['Wed', 'Fri', 'Tue', 'Mon', 'Thu', 'Sat'])
19
Fahad sayyed – notes 11
Linked in @ fahad sayyed
Union of Sets
The union operation on two sets produces a new set containing all the distinct elements
from both the sets. In the below example the element "Wed" is present in both the sets.
The union operator is ‘|’.
DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Wed","Thu","Fri","Sat","Sun"])
AllDays = DaysA|DaysB #Union of Sets
print(AllDays)
When the above code is executed, it produces the following result. Please note the result
has only one "wed".
Intersection of Sets
The intersection operation on two sets produces a new set containing only the common
elements from both the sets. In the below example the element "Wed" is present in both
the sets. The intersection operator is “&”.
DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Wed","Thu","Fri","Sat","Sun"])
AllDays = DaysA & DaysB #Intersection of Sets
print(AllDays)
When the above code is executed, it produces the following result. Please note the result
has only one "wed".
set(['Wed'])
Difference of Sets
The difference operation on two sets produces a new set containing only the elements
from the first set and none from the second set. In the below example the element "Wed"
is present in both the sets so it will not be found in the result set. The operator used is “-”.
DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Wed","Thu","Fri","Sat","Sun"])
AllDays = DaysA - DaysB #Difference of Sets
print(AllDays)
20
Fahad sayyed – notes 11
Linked in @ fahad sayyed
When the above code is executed, it produces the following result. Please note the result
has only one "wed".
set(['Mon', 'Tue'])
Compare Sets
We can check if a given set is a subset or superset of another set. The result is True or False
depending on the elements present in the sets.
DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"])
SubsetRes = DaysA <= DaysB #Check Subset
SupersetRes = DaysB >= DaysA #Check Superset
print(SubsetRes)
print(SupersetRes)
True
True
21