String Lists Tuples Dictionaries: Module-2
String Lists Tuples Dictionaries: Module-2
String
Lists
Tuples
Dictionaries
String
A string is a sequence of characters.
String pythons are immutable.
We can simply create Python String by enclosing a text in single as well as
double quotes. Python treat both single and double quotes statements same.
A character is simply a symbol. For example, the English language has 26
characters.
Computers do not deal with characters, they deal with numbers (binary).
Even though you may see characters on your screen, internally it is stored
and manipulated as a combination of 0's and 1's.
This conversion of character to a number is called encoding, and the reverse
process is decoding. ASCII and Unicode are some of the popular encoding
used.
How to create a string in Python?
my_string = 'Hello’
print(my_string)
my_string = "Hello”
print(my_string)
my_string = '''Hello’’’
print(my_string)
3
If we want to print a text like - He said, "What's there?“
This will result into SyntaxError as the text itself contains both
single and double quotes.
4
Common escape sequences
Sequence Meaning
\\ literal backslash
\' single quote
\" double quote
\n newline
\t tab
5
Python String Formatting
One way to get around this problem is to use triple quotes.
Alternatively, we can use escape sequences.
# using triple quotes
print('''He said, "What's there?“ ''')
# escaping single quotes
print('He said, "What\'s there?"')
# escaping double quotes
print("He said, \"What's there?\"")
6
Accessing Strings:
In Python, Strings are stored as individual characters in a contiguous
memory location.
The benefit of using String is that it can be accessed from both the
directions in forward and backward.
Both forward as well as backward indexing are provided using Strings in
Python.
Forward indexing starts with 0,1,2,3,....
Backward indexing starts with -1,-2,-3,-4,....
7
How to access characters in a string?
• We can access individual characters using indexing and a
range of characters using slicing. Index starts from 0.
• Trying to access a character out of index range will raise an
IndexError. The index must be an integer. We can't use float
or other types, this will result into TypeError.
• Python allows negative indexing for its sequences.
8
String slicing
Example
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
W e l c o m e t o P y t h o n
-17 -16 -15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
9
How to change or delete a string?
• Strings are immutable. This means that elements of a string
cannot be changed once it has been assigned.
• We can simply reassign different strings to the same name.
• We cannot delete or remove characters from a string. But
deleting the string entirely is possible using the keyword del.
my_string = 'programiz'
my_string[5] = ‘e'
TypeError: 'str' object does not support item assignment
my_string = 'Python'
10
Operators to work with strings
11
Concatenation of strings
Length of a String s1 = "Core"
str = "Core Python" s2 = "Python"
print(s1 + s2)
n = len(str)
print("Len: ", n)
Membership Operators
str = input("Enter the first string: ")
Repeating the strings sub = input("Enter the second string: ")
str = "Core Python" if sub in str:
print(str * 2) print(sub +" is found in main string")
else:
print(sub+" is not found in main string")
Methods for the str object
13
string.find(value, start, end)
Parameter Description
value Required. The value to search for
start Optional. Where to start the search. Default is 0
end Optional. Where to end the search. Default is to the end of
the string
14
find()
strip(), lstrip(), rstrip()
txt = "Hello, welcome to my world.“ output:
txt = ",.banan.."
print(txt.find("welcome")) 7 print(txt.strip(',.'))
print(txt.find("e")) 8 print(txt.lstrip())
print(txt.find("e",5, 10)) 1 print(txt.rstrip())
count()
txt = "I apple love banana,apples are my favorite fruit"
x = txt.count("apple",10,27)
print(x)
o/p: 1
string.split(separator, maxsplit)
txt = "apple#banana#cherry#orange"
# setting the maxsplit parameter to 1, will return a list with 2 elements!
x = txt.split("#", 1)
print(x)
16
replace() rfind()
txt = "one one was a race horse, two two was one too." txt = "Mi casa, su casa."
print(txt.replace("one", "three",2)) x = txt.rfind("casa")
print(x)
28
Accessing a list
• Elements are accessed using the index operator [ ]
• Index starting from 0, must be integer
• Index error - Accessing an element out of range
• TypeError – index is not an integer.
• Nested lists are accessed using nested indexing
• >>> n_list = ["Happy", [2,0,1,5]]
• >>> n_list[0][1] # nested indexing
• 'a'
• >>> n_list[1][3] # nested indexing
• 5
29
Negative Indexing
• Sequences(lists, tuples and strings) can have
negative indexing
• Index -1 refers to the last item, -2 refers to second
last and so on.
• >>> my_list = ['p', 'r', 'o', 'b', 'e']
• >>> my_list[-1]
• 'e'
30
List Slicing
• A range of elements in a list can be accessed using
the slicing operator : and two indexes from where
the portion of the list has to be sliced
• >>> my_list = ['p','r','o','g','r','a','m','i','z']
• >>> my_list[2:5] # elements 3rd to 5th
• ['o', 'g', 'r']
• >>> my_list[:-5] #elements beginning to 4th
• ['p', 'r', 'o', 'g']
31
List Slicing….
• >>> my_list[5:] # elements 6th position to
end
• ['a', 'm', 'i', 'z']
• >>> my_list[:] # elements beginning to end
• ['p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z']
32
List Slicing….
• A slice operator on the left can update multiple
elements
• >>> t = ['a', 'b', 'c', 'd', 'e', 'f']
• >>> t[1:3] = ['x', 'y']
• >>> print t
• ['a', 'x', 'y', 'd', 'e', 'f']
33
Changing elements in a list
• = assignment operator is used to modify an item or a range of items in a list
• >>> odd = [2, 4, 6, 8] # mistake values
• >>> odd[0] = 1 # change the 1st item
• >>> odd
• [1, 4, 6, 8]
34
Adding elements to a list
• append() – used to add an item to a list
• extend() – used to add multiple items to a list
• >>> odd = [1, 3, 5]
• >>> odd.append(7)
• >>> odd
• [1, 3, 5, 7]
• >>> odd.extend([9, 11, 13])
• >>> odd
• [1, 3, 5, 7, 9, 11, 13]
• The + operator is used to concatenate two lists
• The * operator is used to repeat a list for a given number of
times
• >>> odd
• [1, 3, 5]
• >>> odd + [9, 7, 5]
• [1, 3, 5, 9, 7, 5]
• >>> ["re"] * 3
• ['re', 're', 're']
Insertion into a list
• insert() – used to insert an item/items at a desired
location
• >>> odd = [1, 9]
• >>> odd.insert(1,3)
• >>> odd
• [1, 3, 9]
• >>> odd[2:2] = [5, 7]
• >>> odd
• [1, 3, 5, 7, 9]
Deleting from a list
• del is used to delete one/more/entire list
• my_list = ['p','r','o','b','l','e','m']
del my_list[2] # delete one item
print(my_list)
o/p: ['p', 'r', 'b', 'l', 'e', 'm']
del my_list[1:5] # delete multiple items
print(my_list)
o/p: ['p', 'm']
del my_list # delete entire list
print(my_list)
... NameError : my_list is not defined.
Deleting from a list
• Remove() – used to remove the first matching
given item
• my_list = ['p','r','o','b','l','e','m']
• >>> my_list.remove('p')
• >>> my_list
• ['r', 'o', 'b', 'l', 'e', 'm']
Deleting from a list
• Pop() – used to remove an item at a given index
>>my_list = ['r', 'o', 'b', 'l', 'e', 'm']
>>> my_list.pop(1)
'o'
>>> my_list
['r', 'b', 'l', 'e', 'm']
Deleting from a list
• Clear() – used to empty a list
my_list = ['r', 'b', 'l', 'e']
my_list.clear()
print(my_list)
o/p: []
Deleting from a list
• A list can also be deleted by assigning an empty list to
a slice of elements
• >>> my_list = ['p','r','o','b','l','e','m']
• >>> my_list[2:3] = []
• >>> my_list
• ['p', 'r', 'b', 'l', 'e', 'm']
• >>> my_list[2:5] = []
• >>> my_list
• ['p', 'r', ‘e’, 'm']
ITERATING OVER LISTS (SEQUENCES)
• Ex 3:
for k in ‘apple’:
print (k)
???????
• Ex 4:
for k in range(0,11):
print (k)
??????
ITERATING OVER LISTS (SEQUENCES)
• Ex 5:
for k in range(2,10,2):
print (k)
???????
• Ex 6:
for k in range(10,-1,-2):
print (k)
??????
Exercise Programs
Pgm. 1
nums = [1,2,3,4,5]
sum = 0
for n in nums:
sum = sum + n
print('Sum =', sum)
Pgm 3
# find the sum and average of all n numbers stored
in a list given by the user.
sum = 0
marks = [] #initialize empty list
size = int(input('Enter size of the list'))
print('Size of the list is', size)
for i in range(0,size):
a= int(input('Enter a number'))
marks.append(a)
for x in marks:
print('Element is', x)
sum = sum + (x)
55
• The sorted() function returns a sorted list of the specified
iterable object.
• a = ("h", "b", "a", "c", "f", "d", "e", "g")
x = sorted(a, reverse=True)
print(x)
56
Assigning and Copying Lists
• A list can be assigned or copied to another list using
the assignment operator =.
• >>>list1 = [10,20,30,40]
• >>>list2 = list1
• >>>list1[0] = 5
• >>>list1
• [5,20,30,40] #change made in list1
• >>>list2
• [5,20,30,40] # change in list1 causes a change in list2
list1 = [10,20,30,40]
list2 = list(list1)
list1[0] = 5
print(list1)
o/p: [5,20,30,40] #change made in list1
print(list2)
o/p: [10,20,30,40] # change in list1 does not cause
any change in list2
Pgm No. 6
# Read two lists of integers. Display whether both lists are of same length,
whether the elements in each list sum up to the same value and whether
there are any values that occur in both the lists.
l1 = []
l2 = []
size = int(input('Enter the total no. of elements'))
print('\nReading list1.........')
for i in range(size):
n = int(input('Enter the next number'))
l1.append(n)
print('\nReading list2.........')
for i in range(size):
n = int(input('Enter the next number'))
l2.append(n)
if len(l1) == len(l2):
print('Both lists are of same size', len(l1), len(l2))
else:
print('Both lists are of different size', len(l1), len(l2))
if sum(l1) == sum(l2):
print('Both lists sum upto same value', sum(l1), sum(l2))
else:
print('Both lists sum upto different values', sum(l1), sum(l2))
for i in l1:
for j in l2:
if i == j:
print(i, 'This value occurs in both lists')
Pgm 7
# Read a list of names. Find how many times the letter 'a' appears in the
list
names = []
count = 0
size = int(input('Enter total number of names'))
for i in range(size):
n = input('Enter a name')
names.append(n)
for i in names:
for j in i:
if j == 'a':
count = count + 1
print('No. of times letter a occurs is ', count)
Pgm No 8.
# To search for an element ‘x’ in a given list of n integers
my_list = []
n = int(input('Enter the size'))
for i in range(n):
num = int(input('Enter the number'))
my_list.append(num)
key = int(input('Enter the search element'))
flag = 1
for i in my_list:
if i == key:
flag = 0
break
if flag == 0:
print(‘Element found’)
else:
print('Element not found')
Pgm 9
# Read a set of names till the user inputs ‘AAA’. Sort these names into
alphabetical order.
names = []
input_names = []
while(1):
name = input('Enter a student name')
if name != 'AAA':
names.append(name)
else:
break
input_names = list(names) #copying lists
print(input_names)
names.sort()
print(input_names)
print('\n The sorted names are‘,names)
List Comprehension
• Range function generates sequence of integers with
fixed increments
• List comprehension is used to generate varied
sequences
• Ex1:
• >>[x ** 2 for x in [1,2,3]]
• >>[1, 4, 9]
Comprehensions in Python
• Comprehensions in Python provide us with a short and concise way
to construct new sequences (such as lists, set, dictionary etc.) using
existing sequences which have been already defined.
Types of comprehensions:
• List Comprehensions
• Dictionary Comprehensions
• Set Comprehensions
• Generator Comprehensions
• Basic structure of List Comprehension:
output_list = [output_exp for var in input_list if (var satisfies this condition)]
- if condition is optional.
- List comprehensions can contain multiple for (nested list comprehensions).
Example:
Create a list of square of all odd numbers from 1 to 10.
# Constructing output list using for loop
output_list = []
for x in range(1, 10):
if x%2==1:
output_list.append(x** 2)
print("Output List using for loop:", output_list)
# Constructing output list
# using list comprehension
74
Pgm 1
inp = []
square = []
positive = []
while(1):
n = int(input('Enter a number'))
if n != 000:
inp.append(n)
else:
break
Pgm 1…..
# using loop
for i in range(0,len(inp)):
square.append(inp[i] * inp[i])
if inp[i] > 0:
positive.append(inp[i])
Pgm 1 using list comprehension…
int = []
#square = []
#positive = []
while(1):
n = int(input('Enter a number'))
if n != 000:
inp.append(n)
else:
break
square = [i* i for i in inp]
print(square)
positive = [i for i in inp if i>0]
print(positive)
Pgm 2 List Comprehension
• Using list comprehension create two lists
1) Odd - list of odd integers from 1 to 10.
2) Even – list of even integers from 1 to 10.
78
Pgm 2
odd = [i for i in range(1,11) if i%2 !=0]
even = [i for i in range(1,11) if i%2 == 0]
print(odd)
print(even)
Nested Lists
• Lists can contain elements of any type…another list
• Ex:
• class_grades = [ [85,91,89], [78, 81, 86], …..]
• is a list of exam scores for each student in a given
class.
• class_grades[0] = [85,91,89]
• class_grades[1] = [78,81,86].
Nested Lists
• The first exam grade of the first student
class_grades[0][0]
o/p: 85.
Pgm 3 Calculate the class average of the first course.
sum = 0
#course_index = 0
for k in range(0, len(class_grades)):
sum = sum + class_grades[k][course_index]
average = sum/float(len(class_grades))
print(‘\n Average in course’, course_index+1, ’is ’, average)
Pgm 4 Average of each course
class_grades = [ [85,91,89], [78, 81, 86] ]
#average in each course
84
a = []
b = []
c = []
nrows = int(input('Enter the no. of rows'))
ncols = int(input('Enter the no. of columns'))
print('Enter Matrix A')
for i in range(0,nrows):
row = [] #initialize a row as a list
print('Enter the elements of row',i)
for j in range(0,ncols):
n = int(input('Enter a number'))
row.append(n) # append this row element to the row list
a.append(row) # append this row to the nested list
print('\n Matrix A is')
for i in a:
print(i)
print('Enter Matrix B')
for i in range(0,nrows):
row = [] #initialize a row as a list
print('Enter the elements of row',i)
for j in range(0,ncols):
n = int(input('Enter a number'))
row.append(n) # append this row element to
# the row list
b.append(row) # append this row to the nested list
print('\n Matrix B is')
for i in b:
print(i)
# Matrix addition using nested loops
for i in range(0,nrows):
row = [] #intialize a row as a list
for j in range(0, ncols):
val = a[i][j] + b[i][j]
row.append(val) # append this row element to
the row list
c.append(row) # append this row to the nested list
Pgm 5
print('The Resultant Matrix')
for i in c:
print(i)
#matrix addition using list comprehension
a=eval(input('enter the first matrix'))
b=eval(input('enter the second matrix'))
sum=[[a[i][j]+ b[i][j] for j in range(len(a[0]))] for i in range(len(a))]
print(sum)
for k in sum:
print(k)
Tuples
• A tuple is an immutable linear data structure.
• In contrast to lists, once a tuple is defined, it
cannot be altered.
• Otherwise tuples are same as lists essentially.
• Tuples are denoted by parenthesis, but tuple
elements are accessed using square brackets.
• Ex:
• num = (10,20,30)
• student = (‘John’, 48, ‘Computer Science’, 3.42)
Creating Tuples…..
• Empty tuple
• >>> tup1 = ()
• Tuples of one element should have a comma following
the element
• Ex: num = (10,)
• >>> my_tuple = ("hello") # only parentheses is not
enough for creating a tuple with one element
• >>> type(my_tuple)
• <class 'str'>
• >>> my_tuple = ("hello",)
• >>> type(my_tuple)
• <class 'tuple'>
Creating Tuples…..
• >>> my_tuple = "hello", # parentheses is
optional
• >>> type(my_tuple)
• <class 'tuple'>
Tuples…..
• Creating a tuple from a list
• list = [1,2,3]
tpl = tuple(list) #converts a list to a tuple
print(tpl)
?????
• Creating a tuple from range()
• tpl = tuple(range(4,9,2))
print(tpl)
??????
Accessing Elements of a Tuple
• my_tuple = ('p','e','r','m','i','t‘)
my_tuple[0]
'p'
my_tuple[6] # index must be in range
IndexError: list index out of range
my_tuple[2.0] # index must be an integer
104
Adding an item to a tuple
#create a tuple
tuplex = (4, 6, 2, 8, 3, 1)
print(tuplex)
#tuples are immutable, so you can not add new
elements.
#using merge of tuples with the + operator you can
add an element and it will create a new tuple
tuplex= tuplex + (9,)
print(tuplex)
105
#adding items in a specific index
tuplex = tuplex[:5] + (15, 20, 25) + tuplex[:5]
print(tuplex)
#converting the tuple to list
listx = list(tuplex)
print(listx)
#use different ways to add items in list
listx.append(30)
tuplex = tuple(listx)
print(tuplex)
106
Converting a tuple to a string
tup = ('e', 'x', 'e', 'r', 'c', 'i', 's', 'e', 's')
str = ''.join(tup)
print(str)
107
Removing an item from a tuple
tuplex = "w", “e”, "r", “i", “d", “e", "r", “s"
print(tuplex)
#tuples are immutable, so you can not remove
elements
#using merge of tuples with the + operator you can
remove an item and it will create a new tuple
#remove "r" from the tuple
tuplex = tuplex[:2] + tuplex[3:]
print(tuplex)
108
Removing…
#converting the tuple to list
listx = list(tuplex)
#use different ways to remove an item of the list
listx.remove("c")
#converting the list to tuple
tuplex = tuple(listx)
print(tuplex)
109
• Write a Python script that prompts the user to enter
types of fruits and their corresponding weight in pounds.
The program should then print the information in the
form of fruit, weight first
a) sorted using alphabetical order of fruit names and then
b) in ascending order of fruit weights and
c)in descending order of fruit weights
Using a list of tuples
• Input : [(‘grapes’,56), (‘orange’,78), (‘apple’, 89)]
111
fruits = ()
for i in range(1,3):
f = ()
name = input('Enter a name')
f.append(name)
weight = input('Enter a weight')
f.append(weight)
fruits.append(f)
print(fruits)
sort_first = sorted(fruits)
sort_second = sorted(fruits, key = operator.itemgetter(1))
sort_third = sorted(fruits, key = operator.itemgetter(1), reverse = 1)
print(sort_first)
print(sort_second)
print(sort_third)
EXERCISES ON TUPLES
1. Create an empty tuple.
t = ()
print(t)
2. Initialize a tuple at compile time.
t = ("Anaconda", 34, 56.99)
print(t)
3. Create a tuple at run time.
ANSWER 1:
#create a list and convert the list to a tuple
age = []
while (1):
a = int(input("Enter the age of a person"))
if a<0:
break
else:
age.append(a)
t = tuple(age)
print(t)
Ans2:
#create an empty tuple and use merge operator
t = ()
while (1):
a = int(input("Enter the age of a person"))
if a<0:
break
else:
t = t + (a,)
print(t)
4. Inserting a set of items into a tuple at a specific index
Ans:
#inserting a tuple into a tuple at a specific index
t = (2,3,4,5,6)
t = t[:2] + (3.1,3.2,3.3,3.4) + t[2:]
print(t)
5. Create a tuple of names and find the number of occurrences of
each name in the tuple.
t = ()
while (1):
a = input("Enter the name of a person")
if a=="AAA":
break
else:
t = t + (a,)
print(t)
unique = []
for i in t:
if i not in unique:
unique.append(i)
print("The name {0} occurs {1} times in the input".format(i,t.count(i)))
6. Modify the above program to find the most frequent name in the list.
Expected O/p: Enter the name of a person:Hary
Enter the name of a person:Potter
Enter the name of a person:Hary
Enter the name of a person:Bob
Enter the name of a person:Alan
Enter the name of a person:AAA
The most frequent name is :Hary
Program:
from statistics import mode
t = ()
while (1):
a = input("Enter the name of a person")
if a == "AAA":
break
else:
t = t + (a,)
print("The most frequent name is", mode(t))
mean() Arithmetic mean (“average”) of data.
fmean() Fast, floating point arithmetic mean.
geometric_mean() Geometric mean of data.
harmonic_mean() Harmonic mean of data.
median() Median (middle value) of data.
median_low() Low median of data.
median_high() High median of data.
median_grouped() Median, or 50th percentile, of grouped data.
mode() Single mode (most common value) of discrete
or nominal data.
multimode() List of modes (most common values) of
discrete or nomimal data.
Divide data into intervals with equal
quantiles() probability.
7. Create a list of names as a tuple. Remove a given name from this list.
Sample Input and Output:
Enter the name of a person : Hary
Enter the name of a person : Potter
Enter the name of a person : Ariana
Enter the name of a person : Stuart
Enter the name of a person : AAA
Enter the name to be removed : Ariana
The list after removing Ariana is : ('Hary', 'Potter', 'Stuart')
t = ()
while (1):
a = input("Enter the name of a person")
if a == "AAA":
break
else:
t = t + (a,)
remove = input("Enter the name to be removed")
for i in range(len(t)):
if t[i] == remove:
t = t[:i] + t[i+1:]
break
print("The list after removing {0} is{1}".format(remove, t))
8. Create a shopping list having the item name and its quantity as a list of tuples.
Ex: The Shopping List [('egg', 3), ('bread', 4), ('butter', 1)]
shopping_list = []
while (1):
a = eval(input("Enter the name and quantity of an item as a ()"))
if a==():
break
else:
shopping_list.append(a)
print("The Shopping List",shopping_list)
Dictionaries
• Indexed data structure - the elements are ordered.
Ex – lists – first element – index 0 and so on
• Associative data structure – elements are unordered and
specified by an associated key-value pair.
• Dictionary – mutable associative data structure of variable length.
Ex: dictionary with average temperatures in a week.
• daily_temp = {‘sun’:68.8, ‘mon’: 72.3, ‘tue’:54.6, ‘wed’:54.2,
‘thur’:76.3, ‘fri’:66.6, ‘sat’:52.1}
Keys are (‘sun’, ‘mon’,…..etc)
127
• Written in curly brackets, where each element are in the
form of key-value pair.
Ex: dictionary with average temperatures in a week.
daily_temp = {‘sun’:68.8, ‘mon’: 72.3, ‘tue’:54.6,
‘wed’:54.2, ‘thur’:76.3, ‘fri’:66.6, ‘sat’:52.1}
Keys are (‘sun’, ‘mon’,…..etc)
Values are 68.8, 72.3, 54.6,……etc.
• Unordered, have named indexes (keys act as indexes).
• Mutable
Dictionaries
• Each element of a dictionary is accessed using its key
Ex: daily_temp[‘mon’]
• No logical first element, second element and so on…
• Keys are generally immutable data types - tuple
Ex: temps = { (‘Jan’, 2, 2004):34.8, (‘Feb’, 6, 2015): 54.7,
(‘Mar’, 12,2007):64.9}
• Red represents key and blue represents value
Accessing Value
• dict1={"apple":50,"orange":20,"banana":30}
• print(dict1["apple"])
• o/p: 50
• print(dict1["orange"])
• o/p:20
• print(dict1["banana"])
• o/p:30
130
Ex: Comparing the temp. of Saturday & Sunday
133
elif day == 'fri':
dayname = 'FRIDAY'
t = temps[5]
elif day=='sat':
dayname = 'SATURDAY'
t = temps[6]
else:
print('Invalid input')
print('The temperature on {0} is {1}'.format(dayname,t))
134
Example2
• Given the daily average temperatures of a
particular week, find the average temperature for
a particular day of the week using a dictionary.
135
#daily temperature using a dictionary
temps = {'sun':68.8, 'mon':70.2,'tue': 67.2,'wed':71.8,'thur': 73.2,'fri': 75.6, 'sat':74.0}
day = input('Enter a day - sun, mon, tue, wed, thur, fri or sat')
print('The temp on {0} is {1}'.format(daynames[day],temps[day]))
136
Operations on a Dictionary
Operation Results
dict() Creates an empty dictionary
Ex: d = dict()
d1 = {}
dict(s) Creates a new dictionary with keys and their associated values from a
sequence, s
Ex: fruit_price = dict(fruit_data)
Where fruit_data is(possibly read from a file)
[[‘apples’,0.66], [‘oranges’, 0.88], ……]
del d[key] Removes key and associated value from the dictionary d
daily_temps={('sun',1): 68.8, ('mon',2): 70.2, ('tue',3): 67.2, ('wed',4): 71.8}
138
3. change value of key (‘mon’,2) in dictionary
daily_temps[('mon',2)]=88.2
print(daily_temps)
o/p:{('sun', 1): 68.8, ('mon', 2): 88.2, ('tue', 3): 67.2, ('wed', 4): 71.8,
('thur', 5): 80.2}
o/p:{('mon', 2): 88.2, ('tue', 3): 67.2, ('wed', 4): 71.8, ('thur', 5): 80.2}
139
Operations on a Dictionary
Operation Results
141
8. Membership Testing
if ('mon',2) in daily_temps:
print("true")
o/p true
if ('sun',1) in daily_temps:
print("true")
else:
print("false")
o/p false
9. Updating a dictionary
dict1={1:10, 2:20}
dict2 ={3:30,4:40}
dict1.update(dict2)
print(dict1)
o/p:{1: 10, 2: 20, 3: 30, 4: 40}
142
Operations on a Dictionary
Operation Results
all(dict) Returns true if all keys of a dictionary are true; false otherwise
any(dict) Returns true if any key of the dictionary is true; false if the
dictionary is empty
sorted(dict) Returns the sorted list of keys
147
• #make a dictionary with each item being a pair of a
number and its square.
>>>squares = {x: x*x for x in range(6)}
>>>print(squares)
# Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
148
EXERCISE PROGRAMS
1. Given an integer number ‘n’, write a program to generate a dictionary with (i, i*i)
such that I is an integer between 1 and n(both included). The program should then
print the dictionary.
Input/Output
Enter a number5
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
n = int(input('Enter a number'))
d = dict()
for i in range(1,n+1):
d[i] = i * i
print(d)
2. Write a Python program to read a list of list having the name of the day and
the corresponding temperature of days in a week
Ex: temps = [[‘sun’, 68.2], [‘mon’,56.6],….]
Convert this to a dictionary. Read a particular day name and its temperature.
Add this to the dictionary only if it doesn’t exists.
Sample Input and Output:
Enter a day and temperature as a list['Sun',34.5]
Enter a day and temperature as a list['Wed',25.8]
The input list is [['Sun', 34.5], ['Wed', 25.8]]
{'Sun': 34.5, 'Wed': 25.8}
Enter a day to add: Tue
Enter a temp: 32
Updated temperatures
{'Sun': 34.5, 'Wed': 25.8, 'Tue': 32.0}
temp_dict = {} #dictionary initialized
temp_list =[] #list of list initialized
for i in range(2):
day_temp = eval(input("Enter a day and temperature as a list"))
temp_list.append(day_temp)
print("The input list is",temp_list)
d= {'even':0,'odd':0}
while(1):
x = int(input("Enter the number"))
if x == -1:
break
if(x%2 == 0):
d['even'] = d['even']+1
else:
d['odd'] = d['odd'] + 1
print(d)
5. Initialize a dictionary {0 : [ ], 1: [ ], 2: [ ], 3: [ ], 4: [ ], 5: [ ], 6: [ ], 7: [ ], 8: [ ]}.
Read any number of integer values from the user till the user inputs -1. Every input integer number
‘n’ has be to be placed in the list whose key is given by n % 9.
INPUT : 9
OUTPUT: {0 : [9], 1: [ ], 2: [ ], 3: [ ], 4: [ ], 5: [ ], 6: [ ], 7: [ ], 8: [ ]}
INPUT : 7
OUTPUT : {0 : [9], 1: [ ], 2: [ ], 3: [ ], 4: [ ], 5: [ ], 6: [ ], 7: [7 ], 8: [ ]}
INPUT : 18
OUTPUT : {0 : [9,18], 1: [ ], 2: [ ], 3: [ ], 4: [ ], 5: [ ], 6: [ ], 7: [ ], 8: [ ]}
d = {0:[], 1:[], 2:[], 3:[], 4:[], 5:[], 6:[], 7:[], 8:[]}
while(1):
x = int(input("Enter the value of n"))
if x == -1:
break
else:
key = x%9
d[key].append(x)
print(d)
6. Create a dictionary having name and mark of students in a class of 3.
Ex: {"JAMES":80,"ROHITH":87,"ISHITHA":67}
The program should then
A )find the number of students in the class B)Find the class average
C)Find the number of students above class average D) Find the topper
E) A student has applied for recheck. Replace the mark of a student given his/her name with the new
mark.
F) Print the updated dictionary
Sample Input and Output:
Enter the IDNO and MARK of each student as a {}{"JAMES":80,"ROHITH":87,"ISHITHA":67}
The student dictionary is {'JAMES': 80, 'ROHITH': 87, 'ISHITHA': 67}
The number of students are 3
The class average is = 78.0
The number of students above class average is 2
The Topper of the class is ROHITH
Who has applied for recheck?ISHITHA
What is the new mark?72
The dictionary after rechecks is {'JAMES': 80, 'ROHITH': 87, 'ISHITHA': 72}
import operator
students = eval(input("Enter the IDNO and MARK of each student as a {}"))
print("The student dictionary is", students)
print("The number of students are",len(students))
# an alternative to find the name with the highest value in the dictionary
#max(students.items(), key = operator.itemgetter(1))[0]
7. Create a dictionary using comprehension from two sequences.
Syntax: {key:value for (key,value) in iterable}
166