Lab 11
Lab 11
LAB # 11
OBJECTIVE
Implement looping through tuple and dictionary and how to access values in
dictionary and also implement adding and removing concept and new key value
pairs in dictionary.
THEORY
Tuples:
A tuple is a sequence of immutable Python objects. Tuples are sequences, just like
lists. The differences between tuples and lists are, the tuples cannot be changed
unlike lists and tuples use parentheses, whereas lists use square brackets.
Creating a tuple is as simple as putting different comma-separated values. Optionally
you can put these comma-separated values between parentheses also. For example
−
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";
The empty tuple is written as two parentheses containing nothing −
tup1 = ();
To write a tuple containing a single value you have to include a comma, even though
there is only one value −
tup1 = (50,);
Example#01
Output:
1
Programming Fundamentals (CT-153) Practical Workbook
Output:
Example#03:
The block at line 1, defines the original tuple and prints the initial dimensions. At line
5, we store a new tuple in the variable dimensions. We then print the new
dimensions at line 6. Python doesn’t raise any errors this time, because overwriting
a variable is valid:
Output:
Dictionary:
A dictionary in Python is a collection of key-value pairs. Each key is connected to a
value, and you can use a key to access the value associated with that key. A key’s
value can be a number, a string, a list, or even another dictionary. Python dictionary
is an unordered collection of items. While other compound data types have only
2
Programming Fundamentals (CT-153) Practical Workbook
value as an element, a dictionary has a key: value pair. Dictionaries can store an
almost limitless amount of information.
Output:
Example#05:
Output:
Example#06:
3
Programming Fundamentals (CT-153) Practical Workbook
Output:
Example#07:
✓ The method items () returns a list of dict's (key, value) tuple pairs. The syntax
of items () method is: dictionary.items ().
✓ The key-value pairs are not returned in the order in which they were stored,
even when looping through a dictionary. Python doesn’t care about the order
in which key-value pairs are stored; it tracks only the connections between
individual keys and their values.
Output:
4
Programming Fundamentals (CT-153) Practical Workbook
Lab Exercise:
1. Write a python program to find the minimum and maximum value (in
numbers) within TUPLE.