Programming Fundamentals
Tuple and Dictionary
Tuple
Sometimes want to create a list of items that cannot
change. Tuples allow you to do just that.
Python refers to values that cannot change as
immutable, and an immutable list is called a tuple.
Tuples are like lists, but their elements are fixed; that
is, once a tuple is created, you cannot add new
elements, delete elements, replace elements, or
reorder the elements in the tuple.
The differences between tuples and lists are, the tuples
cannot be changed unlike lists and tuples use
parentheses, whereas lists use square brackets.
2
Creating a tuple
tup1 = () #empty tuple
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5 ) #tuple of integers
tup3 = "a", "b", "c", "d“ #tuple of characters/string
Example: difference for int and tuple class
tup1 = (50) tup1 = (50,)
print(type(tup1)) print(type(tup1))
Use these code and check the difference in term of data
type.
3
Create a tuple from a list
t3 = tuple([2 * x for x in range(1, 5)]) # (2, 4, 6, 8)
You can also create a tuple from a string. Each character in
the string becomes an element in the tuple. For example:
# Create a tuple from a string
t4 = tuple("abac") # t4 is ['a', 'b’,'a', 'c']
You can use the functions len, min, max, and sum on a
tuple. You can use a for loop to traverse all elements in a
tuple, and can access the elements or slices of the elements
using an index operator.
RQ 4
Example:
tuple1 = ("green", "red", "blue") # Create a tuple
print(tuple1)
tuple2 = tuple([7, 1, 2, 23, 4, 5]) #Create a tuple from a list
print(tuple2)
print("length is", len(tuple2)) #Use function len use functions
print("max is", max(tuple2)) #Use max
print("min is", min(tuple2)) #Use min
print("sum is", sum(tuple2)) #Use sum
print("The first element is", tuple2[0]) #Indexing
tuple3 = tuple1 + tuple2 #Merge two tuple
print(tuple3)
tuple3 = 2 * tuple1 #Duplicate a tuple
print(tuple3)
5
Example
print(2 in tuple2) #in operator
for v in tuple1: #looping
print(v, end = ' ‘)
print()
list1 = list(tuple2) #Obtain a list from a tuple
list1.sort()
t = (1, 2, 3, 7, 9, 0, 5) #Slicing operator
print(t[2 : 4])
print(t[ : -1])
print(t[1 : -1])
6
A tuple takes less memory space in Python:
import sys
l = [1,2,3]
t = (1, 2, 3)
print(sys.getsizeof(l))
print(sys.getsizeof(t))
✓ Lists consume more memory; Tuple consume less
memory as compared to the list
7
Dictionaries
The data structure is called a “dictionary”
because it resembles a word dictionary, where
the words are the keys and the words’
definitions are the values.
A dictionary is a container object that stores a
collection of key/value pairs.
It enables fast retrieval, deletion, and updating
of the value by using the key.
8
A dictionary cannot contain duplicate keys. Each key maps to one value. A
key and its corresponding value form an item (or entry) stored in a dictionary,
as shown in Figure.
Dictionary in Python is an unordered collection of data values, Dictionary
holds key:value pair.
9
Creating dictionary
Create a dictionary by enclosing the items inside a pair
of curly braces {}.
dict1={} #Create an empty dictionary
dict2={1: 'apple', 2: 'ball'} # dictionary with integer
keys
dict3 = {'Name': 'xyz', 1: [1, 2, 3, 4]} #used list in
dictionary
my_dict = {'name':'xyz', 'age': 26} #Accessing Values
in Dictionary
print("value:",my_dict['name’])
print("value:",my_dict.get('age'))
10
#Remove a key from a Python dictionary:
myDict = {'a':1,'b':2,'c':3,'d':4}
print(myDict)
if 'a' in myDict:
del myDict['a’]
print(myDict)
#Sort a Python dictionary by key:
color_dict = {'red':'#FF0000’,
'green':'#008000’,
'black':'#000000’,
'white':'#FFFFFF’}
for key in sorted(color_dict):
print("%s: %s" % (key, color_dict[key]))
11
Program to iterate over dictionaries using for loops:
d = {'x': 10, 'y': 20, 'z': 30}
for dict_key, dict_value in d.items():
print(dict_key,'->',dict_value)
#Program to sum all the items in a dictionary:
my_dict = {'data1':100,'data2':-54,'data3':247}
print(sum(my_dict.values()))
12