C2TI Tuples and Dictionaries
Tuples and Dictionaries
➢ Introduction to 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.
• 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.
• It should be noted that a sequence without parenthesis is treated as tuple by
default.
• We generally use list to store elements of the same data types whereas we
use tuples to store elements of different data types.
➢ 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.
➢ Tuple is Immutable:
• Tuple is an immutable data type.
• 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.
• However an element of a tuple may be of mutable type.
➢ Tuple Operations:
❖ Concatenation:
▪ Python allows us to join tuples using concatenation operator depicted by
symbol +.
▪ We can also create a new tuple which contains the result of this
concatenation operation.
▪ Concatenation operator can also be used for extending an existing tuple.
▪ When we extend a tuple using concatenation a new tuple is created.
❖ Repetition:
▪ Repetition operation is depicted by the symbol *.
▪ It is used to repeat elements of a tuple.
▪ We can repeat the tuple elements.
▪ The repetition operator requires the first operand to be a tuple and the
second operand to be an integer only.
1
C2TI Tuples and Dictionaries
❖ Membership:
▪ The in operator checks if the element is present in the tuple and returns
True, else it returns False.
▪ The not in operator returns True if the element is not present in the tuple,
else it returns False.
❖ Slicing:
▪ Like string and list, slicing can be applied to tuples also.
❖ Tuple Methods and Built-in Functions:
▪ Python provides many functions to work on tuples.
Method Description Example
len() Returns the length or the number of >>> tuple1 = (10,20,30,40,50)
elements of the tuple passed as the >>> len(tuple1)
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')
count() Returns the number of times the >>> tuple1=(10,20,30,10,40,10,50)
given element appears in the tuple >>> tuple1.count (10)
3
index() Returns the index of the first >>> tuple1 = (10,20,30,40,50)
occurrence of the element in the >>> tuple1.index (30)
given tuple 2
sorted() Takes elements in the tuple and >>> tuple1 = ("Rama", "Heena", "Raj",
returns a new sorted list. It should be "Mohsin", "Aditya")
noted that, sorted() does not make >>> sorted(tuple1)
any change to the original tuple ['Aditya', 'Heena', 'Mohsin', 'Raj', 'Rama']
>>> tuple1 = (19,12,56,18,9,87,34)
min() Returns minimum or smallest >>> min(tuple1)
element of the tuple 9
max() Returns maximum or largest element >>> max(tuple1)
of the tuple 87
sum() Returns sum of the elements of the >>> sum(tuple1)
tuple 235
➢ Tuple Assignment:
• Assignment of tuple is a useful feature in Python.
2
C2TI Tuples and Dictionaries
• 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.
• If there is an expression on the right side then first that expression is
evaluated and finally the result is assigned to the tuple.
➢ Nested Tuples:
• A tuple inside another tuple is called a nested tuple.
• \t is an escape character used for adding horizontal tab space.
• Another commonly used escape character is \n, used for inserting a new line.
➢ 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 in which we had entered the data initially in the dictionary.
❖ Creating a Dictionary:
▪ To create a dictionary, the items entered are separated by commas and
enclosed in curly braces.
▪ Each item is a key value pair, separated through colon (:).
▪ The keys in the dictionary must be unique and should be of any
immutable data type, i.e., number, string or tuple.
▪ The values can be repeated and can be of any data type.
❖ Accessing Items in a Dictionary:
▪ We have already seen that the items of a sequence (string, list and tuple)
are accessed using a technique called indexing.
▪ 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.
▪ If the key is not present in the dictionary we get KeyError.
➢ Dictionaries are Mutable:
• Dictionaries are mutable which implies that the contents of the dictionary
can be changed after it has been created.
❖ Adding a new item:
▪ We can add a new item to the dictionary.
❖ Modifying an Existing Item;
▪ The existing dictionary can be modified by just overwriting the key-value
pair.
3
C2TI Tuples and Dictionaries
➢ Dictionary Operations:
❖ Membership:
▪ The membership operator in checks if the key is present in the dictionary
and returns True, else it returns False.
▪ The not in operator returns True if the key is not present in the dictionary,
else it returns False.
➢ Traversing a Dictionary:
• We can access each item of the dictionary or traverse a dictionary using for
loop.
Method 1:
>>> for key in dict1:
print(key,':',dict1[key])
Mohan: 95
Ram: 89
Suhel: 92
Sangeeta: 85
Method 2:
>>> for key,value in dict1.items():
print(key,':',value)
Mohan: 95
Ram: 89
Suhel: 92
Sangeeta: 85
➢ Dictionary methods and Built-in functions:
• Python provides many functions to work on dictionaries. Table lists some of
the commonly used dictionary methods.
4
C2TI Tuples and Dictionaries
Method Description Example
len() Returns the length or number of key: >>> dict1 = {'Mohan':95,'Ram':89, 'Suhel':92,
value pairs of the dictionary passed 'Sangeeta':85}
as the 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)]
keys() Returns a list of keys in the >>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92,
dictionary 'Sangeeta':85}
>>> dict1.keys()
dict_keys(['Mohan', 'Ram', 'Suhel', 'Sangeeta'])
values() Returns a list of values in the >>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92,
dictionary 'Sangeeta':85}
>>> dict1.values()
dict_values([95, 89, 92, 85])
items() Returns a list of tuples(key – value) >>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92,
pair 'Sangeeta':85}
>>> dict1.items()
dict_items([( 'Mohan', 95), ('Ram', 89), ('Suhel',
92), ('Sangeeta', 85)])
get() Returns the value corresponding to >>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92,
the key passed as the argument If 'Sangeeta':85}
the key is not present in the >>> dict1.get('Sangeeta')
dictionary it will return None 85
update() appends the key-value pair of the >>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92,
dictionary passed as the argument 'Sangeeta':85}
to the key-value pair of the given >>> dict2 = {'Sohan':79,'Geeta':89}
dictionary >>> dict1.update(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 given key >>> dict1 = {'Mohan':95,'Ram':89, 'Suhel':92,
To delete the dictionary from the 'Sangeeta':85}
memory we write: >>> del dict1['Ram']
>>> dict1 {'Mohan':95,'Suhel':92, 'Sangeeta': 85}
del Dict_name
clear() Deletes or clear all the items of the >>> dict1 = {'Mohan':95,'Ram':89, 'Suhel':92,
dictionary 'Sangeeta':85}
>>> dict1.clear()
>>> dict1
{}
5
C2TI Tuples and Dictionaries
➢ Manipulating Dictionaries:
• We have learnt how to create a dictionary and apply various methods to
manipulate it (refer the table previously given).
ALL THE BEST