Tuples and Dictionary
Tuples:
A tuple is an ordered sequence of elements of different data types, such as
integer, float, string, list or even a tuple.
Elements of a tuple are enclosed in parenthesis (round brackets) and are
separated by commas.
Like list and string, elements of a tuple can be accessed using index
values, starting from 0.
Examples:
a. tuple1 is the tuple of integers
>>> tuple1 = (1, 2, 3, 4, 5)
>>> tuple1
(1, 2, 3, 4, 5)
b. tuple2 is the tuple of mixed data types
>>> tuple2 = ('Economics', 87,'Accountancy', 89.6)
>>> tuple2
('Economics', 87, 'Accountancy', 89.6)
c. tuple3 is the tuple with list as an element
>>> tuple3 = (10, 20, 30, [40,50])
>>> tuple3
(10, 20, 30, [40, 50])
d. tuple4 is the tuple with tuple as an element
>>> tuple4 = (1, 2, 3, 4, 5, (10, 20))
>>> tuple4
(1, 2, 3, 4, 5, (10, 20))
e. If there is only a single element in a tuple then the element should be
followed by a comma. If we assign the value without comma it is treated as
integer.
tuple5 = (20,) #element followed by comma
>>> tuple5 (20,)
>>>type (tuple5) #tuple5 is of type tuple
<class 'tuple'>
Accessing Elements in a Tuple
Elements of a tuple can be accessed in the same way as a list or string
using indexing and slicing.
a. >>> tuple1 = (2, 4, 6, 8, 10, 12)
>>> tuple1[0] #returns the first element of tuple1
2
b. If tuple index is out of range then returns error
>>> tuple1[15]
IndexError: tuple index out of range
c. If index is an expression resulting in an integer index
>>> tuple1 [1+4]
12
d. Negative indices can be used to access tuple returns first element from
right
>>> tuple1[-1] .
12
Tuple is Immutable:
It means that the elements of a tuple cannot be changed after it has been
created. An attempt to do this would lead to an error.
Output:
TUPLE OPERATIONS
a. Concatenation:
Python allows us to join tuples using concatenation operator depicted
by symbol +.
b. Repetition
Repetition operation is depicted by the symbol *. It is used to repeat
elements of a tuple.
c. Membership
The in operator checks if the element is present in the tuple and returns True,
else it returns False.
d. Slicing:
TUPLE METHODS AND BUILT-IN FUNCTIONS:
Method Description Example
len() Returns the length or the number >>> tuple1 = (10,20,30,40,50)
of elements of the tuple passed as >>> len(tuple1)
the argument 5
tuple() Creates an empty tuple if no >>> tuple1 = tuple()
argument is passed >>> tuple1
()
Creates a tuple if a sequence is >>> tuple1 = tuple('aeiou')#string
passed as argument >>> tuple1
('a', 'e', 'i', 'o', 'u')
>>> tuple2 = tuple([1,2,3]) #list
>>> tuple2
(1, 2, 3)
>>> tuple3 = tuple(range(5))
>>> tuple3
(0, 1, 2, 3, 4)
count() Returns the number of times the >>> tuple1 = (10,20,30,10,40,10,50)
given element appears in the tuple >>> [Link](10)
3
>>> [Link](90)
0
index() Returns the index of the >>> tuple1 = (10,20,30,40,50)
first
occurrence of the element in the >>> [Link](30)
given tuple 2
>>> [Link](90)
ValueError: [Link](x): x not in
tuple
sorted() Takes elements in the tuple and >>> tuple1 = ("Rama","Heena","Raj",
returns a new sorted list. It should "Mohsin","Aditya")
be noted that, sorted() does not
>>> sorted(tuple1)
make any change to the original
tuple ['Aditya', 'Heena', 'Mohsin', 'Raj',
'Rama']
min() Returns minimum tuple1 = (19,12,56,18,9,87,34)
or smallest min(tuple1)
9
element of the tuple
max() Returns maximum or largest tuple1 = (19,12,56,18,9,87,34)
max(tuple1)
element
87
of the tuple
sum() Returns sum of the elements tuple1 = (19,12,56,18,9,87,34)
sum(tuple1)
of the 235
tuple
TUPLE ASSIGNMENT
It allows a tuple of variables on the left side of the assignment operator
to be assigned respective values from a tuple on the right side.
The number of variables on the left should be same as the number of
elements in the tuple.
Example:
a)
2.
Tuple record
created
Record tuple
assigning to another
tuple
3. If right side number of tuple elements are not equals to left side tuple
variables of another tuple then it leads to error.
TUPLE HANDLING:
1. Write a program to swap two numbers without using a temporary variable.
Output:
2. Write a program to compute the area and circumference of a circle using a
function.
Output:
INTRODUCTION TO DICTIONARIES:
The data type dictionary fall under mapping.
It is a mapping between a set of keys and a set of values.
The key-value pair is called an item.
A key is separated from its value by a colon (:) and consecutive items are
separated by commas.
Items in dictionaries are unordered, so we may not get back the data in the
same order.
Creating a Dictionary:
Example:
a. dict1 is an empty Dictionary created #curly braces are used for
dictionary
dict1 = {}
print (dict1)
{}
b. dict2 is an empty dictionary created using built-in function.
dict2 = dict()
print (dict2)
{}
c. dict3 is the dictionary that maps names of the students to respective
marks in percentage.
dict3 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}
dict3
{'Mohan': 95, 'Ram': 89, 'Suhel': 92,'Sangeeta': 85}
Accessing Items in a Dictionary:
The items of a dictionary are accessed via the keys rather than via their
relative positions or indices. Each key serves as the index and maps to a
value.
a. dict3 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}
dict3['Ram']
89
b. the key does not exist
dict3['Shyam']
KeyError: 'Shyam'
DICTIONARIES ARE MUTABLE
Dictionaries are mutable which implies that the contents of the dictionary can
be changed after it has been created.
1. Adding a new item:
We can add a new item to the dictionary as shown in the following
example:
Output:
2. Modifying an Existing Item
The existing dictionary can be modified by just overwriting the key-value
pair.
Output:
Modified
DICTIONARY OPERATIONS:
Membership:
The membership operator in checks if the key is present in the dictionary and
returns True, else it returns False.
Example 1:
dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}
'Suhel' in dict1
True
The not in operator returns True if the key is not present in the dictionary, else it
returns False.
Example 2:
dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}
'Suhel' not in dict1
False
TRAVERSING A DICTIONARY
1. We can access each item of the dictionary or traverse a dictionary using for loop.
Method 1:
Output:
Method 2:
Output:
DICTIONARY METHODS AND BUILT-IN FUNCTIONS:
Method Description Example
len() Returns the length or number >>> dict1 =
of key: value pairs of the {'Mohan':95,'Ram':89,
dictionary passed as the 'Suhel':92, 'Sangeeta':85}
argument
>>> len(dict1) 4
dict() Creates a dictionary from a pair1 = [('Mohan',95),('Ram',89),
sequence of key-value pairs ('Suhel',92),('Sangeeta',85)]
>>> pair1
[('Mohan', 95), ('Ram', 89),
('Suhel',
92), ('Sangeeta', 85)]
>>> dict1 = dict(pair1)
>>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel':
92,
'Sangeeta': 85}
keys() Returns list of keys in >>> dict1 = {'Mohan':95,
a the 'Ram':89, 'Suhel':92,
dictionary 'Sangeeta':85}
>>> [Link]()
dict_keys(['Mohan', 'Ram',
'Suhel', 'Sangeeta'])
values() Returns a list of values in >>> dict1 = {'Mohan':95,
'Ram':89, 'Suhel':92,
the dictionary
'Sangeeta':85}
>>> [Link]()
dict_values([95, 89, 92, 85])
items() Returns a list of tuples(key >>> dict1 = {'Mohan':95,
– 'Ram':89, 'Suhel':92,
'Sangeeta':85}
value) pair
>>> [Link]()
dict_items([( 'Mohan', 95),
('Ram',
89), ('Suhel', 92), ('Sangeeta',
85)])
get() Returns the value >>> dict1 = {'Mohan':95,
corresponding to the key 'Ram':89, 'Suhel':92,
passed as the argument 'Sangeeta':85}
>>> [Link]('Sangeeta') 85
If the key is not present in the >>> [Link]('Sohan')
dictionary it will return None
>>>
update() appends the key-value pair of >>> dict1 = {'Mohan':95,
the dictionary passed as the 'Ram':89, 'Suhel':92,
argument to the key-value 'Sangeeta':85}
pair of the given dictionary
>>> dict2 =
{'Sohan':79,'Geeta':89}
>>> [Link](dict2)
>>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel':
92,
'Sangeeta': 85, 'Sohan': 79,
'Geeta':
89}
>>> dict2
{'Sohan': 79, 'Geeta': 89}
del() Deletes the item with the >>> dict1 =
given key {'Mohan':95,'Ram':89,
To delete the dictionary from 'Suhel':92, 'Sangeeta':85}
the >>> del dict1['Ram']
memory we write:
>>> dict1
del Dict_name
{'Mohan':95,'Suhel':92,
'Sangeeta': 85}
>>> del dict1 ['Mohan']
>>> dict1
{'Suhel': 92, 'Sangeeta': 85}
{'Suhel': 92, 'Sangeeta': 85}
>>> del dict1
>>> dict1
NameError: name 'dict1' is not
defined
clear() Deletes or clear all the items >>> dict1 =
of the dictionary {'Mohan':95,'Ram':89,
'Suhel':92, 'Sangeeta':85}
>>> [Link]()
>>> dict1
{}
MANIPULATING DICTIONARIES:
Create a dictionary ‘ODD’ of odd numbers between 1 and 10, where the key is the decimal
number and the value is the corresponding number in words.
Perform the following operations on this dictionary:
(a) Display the keys
(b) Display the values
(c) Display the items
(d) Find the length of the dictionary