Introduction to Python Programming - 22PLC15B/25B AY:2023-24
MODULE 2
SYLLABUS:
Lists: The List Data Type, Working with Lists, Augmented Assignment Operators, Methods,
Example Program: Magic 8 Ball with a List, List-like Types: Strings and Tuples, References,
Dictionaries and Structuring Data: The Dictionary Data Type, Pretty Printing, Using Data
Structures to Model Real-World Things
Chapter 1
1.1 The list data type
• A list is a value that contains multiple values in an ordered sequence.
• A list begins with an opening square bracket and ends with a closing square bracket, [].
• Values inside the list are also called items.
• Items are separated with commas (that is, they are comma-delimited).
• The value [ ] is an empty list that contains no values, similar to ‘ ’, the empty string.
Examples:
>>> [1, 2, 3]
[1, 2, 3]
>>> ['cat', 'bat', 'rat', 'elephant']
['cat', 'bat', 'rat', 'elephant']
>>> ['hello', 3.1415, True, None, 42]
['hello', 3.1415, True, None, 42]
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam
['cat', 'bat', 'rat', 'elephant']
1.1.1 Getting Individual Values in a List with Indexes
Dept of CSE(IOT), Sir MVIT 1
Introduction to Python Programming - 22PLC15B/25B AY:2023-24
Examples:
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[0]
'cat'
>>> spam[1]
'bat'
>>> spam[2]
'rat'
>>> spam[3]
'elephant'
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> ['cat', 'bat', 'rat', 'elephant'][3]
'elephant'
>>> 'Hello ' + spam[0] # Notice that the expression 'Hello ' + spam[0] evaluates to 'Hello
' + 'cat' because spam[0] evaluates to the string 'cat'.
'Hello cat'
>>> 'The ' + spam[1] + ' ate the ' + spam[0] + '.'
'The bat ate the cat.‘
>>> spam[10000]
Traceback (most recent call last):
File “<pyshell#9>", line 1, in <module>
spam[10000]
IndexError: list index out of range
>>> spam[1.0]
Traceback (most recent call last):
File “<pyshell#13>", line 1, in <module>
spam[1.0]
TypeError: list indices must be integers, not float
>>> spam[int(1.0)]
'bat'
1.1.2 Lists can also contain other list values.
>>> spam = [['cat', 'bat'], [10, 20, 30, 40, 50]]
>>> spam[0]
['cat', 'bat']
Dept of CSE(IOT), Sir MVIT 2
Introduction to Python Programming - 22PLC15B/25B AY:2023-24
>>> spam[0][1]
'bat'
>>> spam[1][4]
50
1.1.3 Negative Indexes
While indexes start at 0 and go up, you can also use negative integers for the index.
The integer value -1 refers to the last index in a list, the value -2 refers to the second-
to-last index in a list, and so on.
Examples:
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[-1]
'elephant'
>>> spam[-3]
'bat'
>>> 'The ' + spam[-1] + ' is afraid of the ' + spam[-3] + '.'
'The elephant is afraid of the bat.'
1.1.4 Getting Sublists with Slices
Just as an index can get a single value from a list.
A slice can get several values from a list, in the form of a new list.
A slice is typed between square brackets, like an index, but it has two integers separated
by a colon.
spam[2] is a list with an index (one integer).
spam[1:4] is a list with a slice (two integers).
spam[1:4]
• In a slice, the first integer is the index where the slice starts & the second integer is the
index where the slice ends.
• Note: A slice goes up to, but will not include, the value at the second index.
• A slice evaluates to a new list value.
Examples:
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[0:4]
['cat', 'bat', 'rat', 'elephant']
>>> spam[1:3]
['bat', 'rat']
>>> spam[0:-1]
Dept of CSE(IOT), Sir MVIT 3
Introduction to Python Programming - 22PLC15B/25B AY:2023-24
['cat', 'bat', 'rat']
• As a shortcut, you can leave out one or both of the indexes on either side of the colon in
the slice.
• Leaving out the first index is the same as using 0, or the beginning of the list.
• Leaving out the second index is the same as using the length of the list, which will slice to
the end of the list.
Examples:
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[:2]
['cat', 'bat']
>>> spam[1:]
['bat', 'rat', 'elephant']
>>> spam[:]
['cat', 'bat', 'rat', 'elephant']
1.1.5 Getting a List’s Length with len()
The len() function will return the number of values that are in a list value passed to it.
Example:
>>> spam = ['cat', 'dog', 'moose']
>>> len(spam)
3
1.1.6 Changing Values in a List with Indexes
Use an index of a list to change the value at that index.
For example, spam[1] = ‘TIGER’ means “Assign the value at index 1 in the list spam
to the string ' TIGER '.”
Examples:
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[1] = ‘TIGER'
>>> spam
['cat', ' TIGER ', 'rat', 'elephant']
>>> spam[2] = spam[1]
Dept of CSE(IOT), Sir MVIT 4
Introduction to Python Programming - 22PLC15B/25B AY:2023-24
>>> spam
['cat', ' TIGER ', ' TIGER ', 'elephant']
>>> spam[-1] = 12345
>>> spam
['cat', ' TIGER ', ' TIGER ', 12345]
1.1.7 List Concatenation and List Replication
The + operator can combine two lists to create a new list value in the same way it
combines two strings into a new string value.
The * operator can also be used with a list and an integer value to replicate the list.
Examples
>>> [1, 2, 3] + ['A', 'B', 'C']
[1, 2, 3, 'A', 'B', 'C']
>>> ['X', 'Y', 'Z'] * 3
['X', 'Y', 'Z', 'X', 'Y', 'Z', 'X', 'Y', 'Z']
>>> spam = [1, 2, 3]
>>> spam = spam + ['A', 'B', 'C']
>>> spam
[1, 2, 3, 'A', 'B', 'C']
1.1.8 Removing Values from Lists with del Statements
The del statement will delete values at an index in a list.
All of the values in the list after the deleted value will be moved up one index.
Example
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> del spam[2]
>>> spam
['cat', 'bat', 'elephant']
>>> del spam[2]
>>> spam
['cat', 'bat']
Dept of CSE(IOT), Sir MVIT 5
Introduction to Python Programming - 22PLC15B/25B AY:2023-24
1.2 Working with lists
Example 1: (Without Lists)
print('Enter the name of cat 1:')
catName1 = input()
print('Enter the name of cat 2:')
catName2 = input()
print('Enter the name of cat 3:')
catName3 = input()
print('Enter the name of cat 4:')
catName4 = input()
print('Enter the name of cat 5:')
catName5 = input()
print('Enter the name of cat 6:')
catName6 = input()
print('The cat names are:')
print(catName1 + ' ' + catName2 + ' ' + catName3 + ' ' + catName4 + ' ' + catName5 + ' ' +
catName6)
Output:
Enter the name of cat 1:
andy
Enter the name of cat 2:
sandy
Enter the name of cat 3:
pandy
Enter the name of cat 4:
landy
Enter the name of cat 5:
candy
Enter the name of cat 6:
mandy
The cat names are:
andy sandy pandy landy candy mandy
Dept of CSE(IOT), Sir MVIT 6
Introduction to Python Programming - 22PLC15B/25B AY:2023-24
Example 2: (Same Program with LIST)
catNames = []
while True:
print('Enter the name of cat ' + str(len(catNames) + 1) + ' (Or enter nothing to stop.):')
name = input()
if name == '':
break
catNames = catNames + [name] # list concatenation
print('The cat names are:')
for name in catNames:
print(' ' + name)
Output:
Enter the name of cat 1 (Or enter nothing to stop.):
andy
Enter the name of cat 2 (Or enter nothing to stop.):
sandy
Enter the name of cat 3 (Or enter nothing to stop.):
mandy
Enter the name of cat 4 (Or enter nothing to stop.):
pandy
Enter the name of cat 5 (Or enter nothing to stop.):
londy
Enter the name of cat 6 (Or enter nothing to stop.):
The cat names are:
andy
sandy
mandy
pandy
Dept of CSE(IOT), Sir MVIT 7
Introduction to Python Programming - 22PLC15B/25B AY:2023-24
londy
1.3 Using for Loops with Lists
A for loop repeats the code block once for each value in a list or list-like value.
Example 1:
for i in [0, 1, 2, 3]:
print(i)
Output:
2
3
Example 2:
supplies = ['pens', 'staplers', ‘markers', 'binders']
for i in range(len(supplies)):
print('Index ' + str(i) + ' in supplies is: ' + supplies[i])
Output:
Index 0 in supplies is: pens
Index 1 in supplies is: staplers
Index 2 in supplies is: markers
Index 3 in supplies is: binders
1.4 The in and not in Operators
You can determine whether a value is or isn’t in a list with the in and not in operators.
Like other operators, in and not in are used in expressions and connect two values: a
value to look for in a list and the list where it may be found.
Example 1:
>>> 'howdy' in ['hello', 'hi', 'howdy', 'hurrah']
True
>>> spam = ['hello', 'hi', 'howdy', ‘hurrah']
>>> 'cat' in spam
False
Dept of CSE(IOT), Sir MVIT 8
Introduction to Python Programming - 22PLC15B/25B AY:2023-24
>>> 'howdy' not in spam
False
>>> 'cat' not in spam
True
Example 2:
myPets = ['Zophie', ‘ZooZoo', 'Fat-tail']
print('Enter a pet name:')
name = input()
if name not in myPets:
print('I do not have a pet named ' + name)
else:
print(name + ' is my pet.')
Output:
Enter a pet name:
ZOO
I do not have a pet named ZOO
1.5 The Multiple Assignment Trick
The multiple assignment trick is a shortcut that lets you assign multiple variables with the
values in a list in one line of code.
Examples:
>>> cat = ['fat', 'black', ‘ZooZoo']
>>> size = cat[0]
>>> color = cat[1]
>>> name = cat[2]
you could type this line of code:
>>> cat = ['fat', 'black', 'ZooZoo']
>>> size, color, name = cat
1.6 Augmented Assignment operators
Examples:
>>> spam = 42
>>> spam = spam + 1
>>> spam
43
Replace With
>>> spam = 42
>>> spam += 1
>>> spam
43
Dept of CSE(IOT), Sir MVIT 9
Introduction to Python Programming - 22PLC15B/25B AY:2023-24
The augmented assignment operators for the +, -, *, /, and % operators
Augmented assignment statement Equivalent assignment statement
spam = spam + 1 spam += 1
spam = spam - 1 spam -= 1
spam = spam * 1 spam *= 1
spam = spam / 1 spam /= 1
spam = spam % 1 spam %= 1
• The += operator can also do string and list concatenation, and the *= operator can do string
and list replication.
• Example
>>> spam = 'Hello'
>>> spam += ' world!'
>>> spam
'Hello world!'
>>> bacon = ['Zophie']
>>> bacon *= 3
>>> bacon
['Zophie', 'Zophie', 'Zophie']
1.7 LIST Methods
index
append
insert
remove
sort
1.7.1 index() - Finding a Value in a List with the index() Method
Example:
>>> spam = ['hello', 'hi', 'howdy', 'heyas']
>>> spam.index('hello')
0
>>> spam.index('heyas')
3
>>> spam = ['Zophie', ‘ZooZoo', 'Fat-tail', ' ZooZoo']
>>> spam.index(‘ZooZoo')
1
Dept of CSE(IOT), Sir MVIT 10
Introduction to Python Programming - 22PLC15B/25B AY:2023-24
1.7.2 append() - Adding Values to Lists with the append() Method.
Example:
>>> spam = ['cat', 'dog', 'bat']
>>> spam.append(‘rat')
>>> spam
['cat', 'dog', 'bat', ‘rat']
1.7.3 insert() - Adding Values to Lists with the insert() Method.
Example:
>>> spam = ['cat', 'dog', 'bat']
>>> spam.insert(1, 'rat')
>>> spam
['cat', 'rat', 'dog', 'bat']
Note:
• Methods belong to a single data type.
• The append() and insert() methods are list methods and can be called only on list values,
not on other values such as strings or integers.
Example:
>>> eggs = 'hello'
>>> eggs.append('world')
AttributeError: 'str' object has no attribute 'append'
>>> bacon = 42
>>> bacon.insert(1, 'world')
AttributeError: 'int' object has no attribute 'insert'
1.7.4 remove() - Removing Values from Lists with remove()
Examples:
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam.remove('bat')
>>> spam
['cat', 'rat', 'elephant']
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam.remove('chicken')
ValueError: list.remove(x): x not in list
Dept of CSE(IOT), Sir MVIT 11
Introduction to Python Programming - 22PLC15B/25B AY:2023-24
>>> spam = ['cat', 'bat', 'rat', 'cat', 'hat', 'cat']
>>> spam.remove('cat')
>>> spam
['bat', 'rat', 'cat', 'hat', 'cat']
1.7.5 sort() - Sorting the Values in a List with the sort() Method
Examples:
>>> spam = [2, 5, 3.14, 1, -7]
>>> spam.sort()
>>> spam
[-7, 1, 2, 3.14, 5]
>>> spam = ['ants', 'cats', 'dogs', 'bats', 'elephants']
>>> spam.sort()
>>> spam
['ants', 'bats', 'cats', 'dogs', 'elephants']
1.7.5.1 Sort the values in reverse order.
You can also pass True for the reverse keyword argument to have sort() sort the values
in reverse order.
Example:
>>> spam.sort(reverse=True)
>>> spam
['elephants', 'dogs', 'cats', 'badgers', 'ants']
Three things to know about sorting
1. The sort() method sorts the list in place; don’t try to capture the return value by writing
code like spam = spam.sort().
2. You cannot sort lists that have both number values and string values in them, since Python
doesn’t know how to compare these values.
3. Sort() uses “ASCIIbetical order” rather than actual alphabetical order for sorting strings.
This means uppercase letters come before lowercase letters.
Example:
>>> spam = [1, 3, 2, 4, 'Alice', 'Bob']
>>> spam.sort()
TypeError: unorderable types: str() < int()
>>> spam = ['Alice', 'ants', 'Bob', 'badgers', 'Carol', 'cats']
>>> spam.sort()
>>> spam
['Alice', 'Bob', 'Carol', 'ants', 'badgers', 'cats']
>>> spam = ['a', 'z', 'A', 'Z']
>>> spam.sort(key=str.lower)
>>> spam
['a', 'A', 'z', 'Z']
Dept of CSE(IOT), Sir MVIT 12
Introduction to Python Programming - 22PLC15B/25B AY:2023-24
Note: The above causes the sort() function to treat all the items in the list as if they were
lowercase without actually changing the values in the list.
1.8 Example Program: magic 8 Ball with a list
Example 1: Without List
import random
def getAnswer(answerNumber):
if answerNumber == 1:
return 'It is certain‘
elif answerNumber == 2:
return 'It is decidedly so‘
elif answerNumber == 3:
return 'Yes‘
elif answerNumber == 4:
return 'Reply hazy try again‘
elif answerNumber == 5:
return 'Ask again later‘
elif answerNumber == 6:
return 'Concentrate and ask again‘
elif answerNumber == 7:
return 'My reply is no‘
elif answerNumber == 8:
return 'Outlook not so good‘
elif answerNumber == 9:
return 'Very doubtful'
r = random.randint(1, 9)
fortune = getAnswer(r)
print(fortune)
Output:
Outlook not so good (It will Vary every time when you the run the code)
Example 2: With List
import random
messages = ['It is certain',
'It is decidedly so',
'Yes definitely',
'Reply hazy try again',
'Ask again later',
Dept of CSE(IOT), Sir MVIT 13
Introduction to Python Programming - 22PLC15B/25B AY:2023-24
'Concentrate and ask again',
'My reply is no',
'Outlook not so good',
'Very doubtful']
print(messages[random.randint(0, len(messages) - 1)])
Output:
Very doubtful (It will Vary every time when you the run the code)
1.9 list-like types: Strings and tuples
Lists aren’t the only data types that represent ordered sequences of values.
For example, strings and lists are actually similar, if you consider a string to be a “list”
of single text characters.
Many of the things you can do with lists can also be done with strings: indexing;
slicing; and using them with for loops, with len(), and with the in and not in operators.
Example:
>>> name = 'Zophie'
>>> name[0]
'Z'
>>> name[-2]
'i'
>>> name[0:4]
'Zoph'
>>> 'Zo' in name
True
>>> 'z' in name
False
>>> 'p' not in name
False
>>> for i in name:
print('* * * ' + i + ' * * *')
***Z***
***o***
***p***
***h***
***i***
***e***
1.10 Mutable and Immutable Data Types
But lists and strings are different in an important way.
A list value is a mutable data type: It can have values added, removed, or changed.
Dept of CSE(IOT), Sir MVIT 14
Introduction to Python Programming - 22PLC15B/25B AY:2023-24
However, a string is immutable: It cannot be changed.
Trying to reassign a single character in a string results in a TypeError error.
Example
>>> name = 'Zophie a cat'
>>> name[7] = 'the‘
TypeError: 'str' object does not support item assignment
The proper way to “mutate” a string is to use slicing and concatenation to build a new string by
copying from parts of the old string.
>>> name = 'Zophie a cat'
>>> newName = name[0:7] + 'the' + name[8:12]
>>> name
‘Zophie a cat’
>>> newName
‘Zophie the cat’
1.10.1 A list value is mutable: Example 1
Example 1:
>>> eggs = [1, 2, 3]
>>> eggs = [4, 5, 6]
>>> eggs
[4, 5, 6]
Example 2:
>>> eggs = [1, 2, 3]
>>> del eggs[2]
>>> del eggs[1]
>>> del eggs[0]
>>> eggs.append(4)
>>> eggs.append(5)
>>> eggs.append(6)
>>> eggs
Dept of CSE(IOT), Sir MVIT 15
Introduction to Python Programming - 22PLC15B/25B AY:2023-24
[4, 5, 6]
1.11 The Tuple Data Type
The tuple data type is almost identical to the list data type, except in two ways.
First, tuples are typed with parentheses, ( and ), instead of square brackets, [ and ].
Tuples are different from lists is that tuples, like strings, are immutable (Tuples cannot
have their values modified, appended, or removed).
Example:
>>> eggs = ('hello', 42, 0.5)
>>> eggs[1] = 99
TypeError: 'tuple' object does not support item assignment
• If you have only one value in your tuple, you can indicate this by placing a trailing comma
after the value inside the parentheses.
>>> type(('hello',))
<class 'tuple'>
>>> type(('hello'))
<class 'str'>
• Otherwise, Python will think you’ve just typed a value inside regular parentheses.
• The comma is what lets Python know this is a tuple value.
1.12 Converting Types with the list() and tuple() Functions
Example:
>>> tuple(['cat', 'dog', 5])
('cat', 'dog', 5)
>>> list(('cat', 'dog', 5))
['cat', 'dog', 5]
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
1.13 References (Example 1- assigning values to variables):
Example 1:
>>> spam = 42
>>> cheese = spam
Dept of CSE(IOT), Sir MVIT 16
Introduction to Python Programming - 22PLC15B/25B AY:2023-24
>>> spam = 100
>>> spam
100
>>> cheese
42
Example 2 - assign a list to a variable
>>> spam = [0, 1, 2, 3, 4, 5]
>>> cheese = spam
>>> cheese[1] = ‘Hello!’
>>> spam
[0, 'Hello!', 2, 3, 4, 5]
>>> cheese
[0, 'Hello!', 2, 3, 4, 5]
1.13.1 Passing References
Pass means to provide an argument to a function.
By reference means that the argument you’re passing to the function is a reference to
a variable that already exists in memory rather than an independent copy of that
variable.
Example:
def eggs(someParameter):
someParameter.append('Hello')
spam = [1, 2, 3]
eggs(spam)
print(spam)
Dept of CSE(IOT), Sir MVIT 17
Introduction to Python Programming - 22PLC15B/25B AY:2023-24
1.14 The copy Module’s copy() and deepcopy() Functions
Python provides a module named copy that provides both the copy() and deepcopy()
functions.
The first of these, copy.copy(), can be used to make a duplicate copy of a mutable value
like a list or dictionary, not just a copy of a reference.
If the list you need to copy contains lists, then use the copy.deepcopy() function instead
of copy.copy(). The deepcopy() function will copy these inner lists as well.
Example 1:
Copy:
a = [[1, 2, 3], [4, 5, 6]]
>>> b = list(a)
>>> a
[[1, 2, 3], [4, 5, 6]]
>>> b
[[1, 2, 3], [4, 5, 6]]
>>> a[0][1] = 10
>>> a
[[1, 10, 3], [4, 5, 6]]
>>> b # b changes too -> Not a deepcopy.
[[1, 10, 3], [4, 5, 6]]
Deep Copy:
>>> import copy
>>> b = copy.deepcopy(a)
>>> a
[[1, 10, 3], [4, 5, 6]]
>>> b
[[1, 10, 3], [4, 5, 6]]
>>> a[0][1] = 9
>>> a
[[1, 9, 3], [4, 5, 6]]
>>> b # b doesn't change -> Deep Copy
[[1, 10, 3], [4, 5, 6]]
Example 2:
>>>import copy
>>> spam = ['A', 'B', 'C', 'D']
>>> cheese = copy.copy(spam)
Dept of CSE(IOT), Sir MVIT 18
Introduction to Python Programming - 22PLC15B/25B AY:2023-24
>>> cheese[1] = 42
>>> spam
['A', 'B', 'C', 'D']
>>> cheese
['A', 42, 'C', 'D']
Dept of CSE(IOT), Sir MVIT 19
Introduction to Python Programming - 22PLC15B/25B AY:2023-24
Chapter 2: Dictionaries and Structuring Data
2.1 The dictionary data type:
• Like a list, a dictionary is a collection of many values.
• But unlike indexes for lists, indexes for dictionaries can use many different data types, not
just integers.
• Indexes for dictionaries are called keys, and a key with its associated value is called a key-
value pair.
• In code, a dictionary is typed with braces, { }.
Example:
>>> myCat = {'size': 'fat', 'color': 'gray', 'disposition': 'loud'}
• This assigns a dictionary to the myCat variable.
• This dictionary’s keys are 'size', 'color', and 'disposition'.
• The values for these keys are 'fat', 'gray', and 'loud', respectively.
>>> myCat['size']
'fat'
>>> 'My cat has ' + myCat['color'] + ' fur.'
'My cat has gray fur.'
>>> spam = {12345: 'Luggage Combination', 42: 'The Answer'}
2.2 Dictionaries vs. Lists
• Items in dictionaries are unordered.
• The first item in a list named spam would be spam[0].
• But there is no “first” item in a dictionary.
• The order of items matters for determining whether two lists are the same.
• It does not matter in what order the key-value pairs are typed in a dictionary.
Examples:
>>> d1 = ['cats', 'dogs', 'moose']
>>> d2 = ['dogs', 'moose', 'cats']
>>> d1 == d2
False
Dept of CSE(IOT), Sir MVIT 20
Introduction to Python Programming - 22PLC15B/25B AY:2023-24
>>> d3 = {'name': 'Zophie', 'species': 'cat', 'age': '8'}
>>> d4 = {'species': 'cat', 'age': '8', 'name': 'Zophie'}
>>> d3 == d4
True
Note: Dictionaries are not ordered, they can’t be sliced like lists.
>>> spam = {'name': 'Zophie', 'age': 7}
>>> spam['color']
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
spam['color']
KeyError: 'color’
2.2.1 Program to store data about your friends’ birthdays.
Hint: You can use a dictionary with the names as keys and the birthdays as values.
birthdays = {'Alice': 'Apr 1', 'Bob': 'Dec 12', 'Carol': 'Mar 4'}
while True:
print('Enter a name: (blank to quit)')
name = input()
if name == '':
break
if name in birthdays:
print(birthdays[name] + ' is the birthday of ' + name)
else:
print('I do not have birthday information for ' + name)
print('What is their birthday?')
bday = input()
birthdays[name] = bday
print('Birthday database updated.')
Output:
Dept of CSE(IOT), Sir MVIT 21
Introduction to Python Programming - 22PLC15B/25B AY:2023-24
Enter a name: (blank to quit)
Cheesy
I do not have birthday information for Cheesy
What is their birthday?
31/01/2020
Birthday database updated.
Enter a name: (blank to quit)
Alice
Apr 1 is the birthday of Alice
Enter a name: (blank to quit)
2.3 The keys(), values(), and items() Methods
• There are three dictionary methods that will return list-like values of the dictionary’s keys,
values, or both keys and values: keys(), values(), and items().
• The values returned by these methods are not true lists: They cannot be modified and do
not have an append() method.
• But these data types can be used in for loops.
Example 1:
>>> spam = {'color': 'red', 'age': 42}
>>> for v in spam.values():
print(v)
Output:
red
42
>>> for k in spam.keys():
print(k)
Output:
color
age
Dept of CSE(IOT), Sir MVIT 22
Introduction to Python Programming - 22PLC15B/25B AY:2023-24
>>> for i in spam.items():
print(i)
Output:
('color', 'red')
('age', 42)
Example 2:
>>> spam = {'color': 'red', 'age': 42}
>>> spam.keys()
dict_keys (['color', 'age'])
>>> list(spam.keys())
['color', 'age']
>>> spam = {'color': 'red', 'age': 42}
>>> for k, v in spam.items():
print('Key: ' + k + ' Value: ' + str(v))
Key: age Value: 42
Key: color Value: red
2.4 Checking Whether a Key or Value Exists in a Dictionary (in and not in)
>>> spam = {'name': 'Zophie', 'age': 7}
>>> 'name' in spam.keys()
True
>>> 'Zophie' in spam.values()
True
>>> 'color' in spam.keys()
False
>>> 'color' not in spam.keys()
True
>>> 'color' in spam
Dept of CSE(IOT), Sir MVIT 23
Introduction to Python Programming - 22PLC15B/25B AY:2023-24
False
2.5 The get() Method
• Python get() method return the value for the given key if present in the dictionary.
• If not, then it will return None.
Syntax:
dictionary.get(keyname, value)
Parameter Values
Parameter Description
keyname Required. The keyname of the item you want to return the
value.
value Optional. A value to return if the specified key does not exist.
Default value None
Example 1:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.get("model")
print(x)
Output:
Mustang
Example 2:
dic = {"A": 1, "B": 2}
print(dic.get("A"))
print(dic.get("C"))
print(dic.get("C", "Not Found ! "))
Dept of CSE(IOT), Sir MVIT 24
Introduction to Python Programming - 22PLC15B/25B AY:2023-24
Output:
1
None
Not Found !
2.6 setdefault() method
• In Python Dictionary, setdefault() method returns the value of a key (if the key is in
dictionary).
• If not, it inserts key with a value to the dictionary.
Syntax
dictionary.setdefault(keyname, value)
Parameter Values
Parameter Description
keyname Required. The keyname of the item you want to return the value
from
value Optional.
* If the key exist, this parameter has no effect.
* If the key does not exist, this value becomes the key's value
* Default value None
Example 1:
Dictionary1 = { 'A': 'Geeks', 'B': 'For', 'C': 'Geeks'}
Third_value = Dictionary1.setdefault('C')
print("Dictionary:", Dictionary1)
print("Third_value:", Third_value)
Output:
Dictionary: {'A': 'Geeks', 'B': 'For', 'C': 'Geeks'}
Third_value: Geeks
Example 2 : When key is not in the dictionary.
Dictionary1 = { 'A': 'Geeks', 'B': 'For'}
Dept of CSE(IOT), Sir MVIT 25
Introduction to Python Programming - 22PLC15B/25B AY:2023-24
# when key is not in the Dictionary
Third_value = Dictionary1.setdefault('C')
print("Dictionary:", Dictionary1)
print("Third_value:", Third_value)
# but default value is provided
Fourth_value = Dictionary1.setdefault('D', 'Geeks')
print("Dictionary:", Dictionary1)
print("Fourth_value:", Fourth_value)
Output:
Dictionary: {'A': 'Geeks', 'B': 'For', 'C': None}
Third_value: None
Dictionary: {'A': 'Geeks', 'B': 'For', 'C': None, 'D': 'Geeks'}
Fourth_value: Geeks
Note:
• To access dictionary elements, you can use the familiar square brackets along with the key
to obtain its value.
2.7 Python program for counting how often each character appears.
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
print(count)
Output:
{'I': 1, 't': 6, ' ': 13, 'w': 2, 'a': 4, 's': 3, 'b': 1, 'r': 5, 'i': 6, 'g': 2, 'h': 3, 'c': 3, 'o': 2, 'l':
3, 'd': 3, 'y': 1, 'n': 4, 'A': 1, 'p': 1, ',': 1, 'e': 5, 'k': 2, '.': 1}
2.8 Pretty Printing
• The pprint() and pformat() functions that will “pretty print” a dictionary’s values.
Dept of CSE(IOT), Sir MVIT 26
Introduction to Python Programming - 22PLC15B/25B AY:2023-24
• This is helpful when you want a cleaner display of the items in a dictionary than what
print() provides.
Example:
import pprint
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
pprint.pprint(count)
Output:
{' ': 13,
',': 1,
'.': 1,
'A': 1,
'I': 1,
'a': 4,
'b': 1,
'c': 3,
'd': 3,
'e': 5,
'g': 2,
'h': 3,
'i': 6,
'k': 2,
'l': 3,
'n': 4,
'o': 2,
'p': 1,
Dept of CSE(IOT), Sir MVIT 27
Introduction to Python Programming - 22PLC15B/25B AY:2023-24
'r': 5,
's': 3,
't': 6,
'w': 2,
'y': 1}
2.9 Using Data Structures to Model Real-World Thing
Example: A Tic Tac Toe Board
STEP 1:
theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ', 'mid-L': ' ', 'mid-M': ' ', 'mid-R': ' ', 'low-L': '
', 'low-M': ' ', 'low-R': ' '}
STEP 2:
theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ', 'mid-L': ' ', 'mid-M': 'X', 'mid-R': ' ', 'low-L': '
', 'low-M': ' ', 'low-R': ' '}
STEP 3:
theBoard = {'top-L': 'O', 'top-M': 'O', 'top-R': 'O', 'mid-L': 'X', 'mid-M': 'X', 'mid-R': ' ', 'low-
L': ' ', 'low-M': ' ', 'low-R': 'X'}
Dept of CSE(IOT), Sir MVIT 28
Introduction to Python Programming - 22PLC15B/25B AY:2023-24
STEP 4:
theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ',
'mid-L': ' ', 'mid-M': ' ', 'mid-R': ' ',
'low-L': ' ', 'low-M': ' ', 'low-R': ' '}
def printBoard(board):
print(board['top-L'] + '|' + board['top-M'] + '|' + board['top-R'])
print('-+-+-')
print(board['mid-L'] + '|' + board['mid-M'] + '|' + board['mid-R'])
print('-+-+-')
print(board['low-L'] + '|' + board['low-M'] + '|' + board['low-R'])
printBoard(theBoard)
STEP 5:
theBoard = {'top-L': 'O', 'top-M': 'O', 'top-R': 'O', 'mid-L': 'X', 'mid-M':
'X', 'mid-R': ' ', 'low-L': ' ', 'low-M': ' ', 'low-R': 'X'}
def printBoard(board):
print(board['top-L'] + '|' + board['top-M'] + '|' + board['top-R'])
print('-+-+-')
print(board['mid-L'] + '|' + board['mid-M'] + '|' + board['mid-R'])
print('-+-+-')
print(board['low-L'] + '|' + board['low-M'] + '|' + board['low-R'])
Dept of CSE(IOT), Sir MVIT 29
Introduction to Python Programming - 22PLC15B/25B AY:2023-24
printBoard(theBoard)
STEP 6: ASSIGNMENT
• Add code that allows the players to enter their moves
theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ', 'mid-L': ' ', 'mid-M': ' ', 'mid-R': ' ', 'low-L': '
', 'low-M': ' ', 'low-R': ' '}
def printBoard(board):
print(board['top-L'] + '|' + board['top-M'] + '|' + board['top-R']) print(‘ +-+-')
print(board['mid-L'] + '|' + board['mid-M'] + '|' + board['mid-R'])
print('-+-+-') print(board['low-L'] + '|' + board['low-M'] + '|' +
board['low-R'])
turn = 'X'
for i in range(9):
printBoard(theBoard)
print('Turn for ' + turn + '. Move on which space?')
move = input()
theBoard[move] = turn
if turn == 'X':
turn = 'O'
else:
turn = 'X'
printBoard(theBoard)
2.9.1 Nested Dictionaries and Lists
• Example:
allGuests = {'Alice': {'apples': 5, 'pretzels': 12}, 'Bob': {'ham
Dept of CSE(IOT), Sir MVIT 30
Introduction to Python Programming - 22PLC15B/25B AY:2023-24
sandwiches': 3, 'apples': 2}, 'Carol': {'cups': 3, 'apple pies': 1}}
• A program that uses a dictionary that contains other dictionaries in order to see who is
bringing what to a picnic
Example:
allGuests = {'Alice': {'apples': 5, 'pretzels': 12}, 'Bob': {'ham sandwiches': 3, 'apples': 2},
'Carol': {'cups': 3, 'apple pies': 1}}
def totalBrought(guests, item):
numBrought = 0
for k, v in guests.items():
numBrought = numBrought + v.get(item, 0)
return numBrought
print('Number of things being brought:')
print(' - Apples ' + str(totalBrought(allGuests, 'apples')))
print(' - Cups ' + str(totalBrought(allGuests, 'cups')))
print(' - Cakes ' + str(totalBrought(allGuests, 'cakes')))
print(' - Ham Sandwiches ' + str(totalBrought(allGuests, 'ham sandwiches')))
print(' - Apple Pies ' + str(totalBrought(allGuests, 'apple pies')))
Dept of CSE(IOT), Sir MVIT 31
Introduction to Python Programming - 22PLC15B/25B AY:2023-24
VTU OLD QUESTION PAPER QUESTIONS
1. What is the difference between copy.copy() and copy.deepcopy() function applicable to a
list or dictionary in python? Give suitable examples for each. (July/August 2022 – 6M)
2. Write a python to swap cases of a given string. (July/August 2022 – 4M)
Input: Java
Output: jAVA
3. What is List? Explain append(), insert() and remove() methods with examples. (Jan/Feb
2021 – 8M)
4. How is tuple different from a list and which function is used to convert list to tuple.
(Jan/Feb 2021 – 5M)
5. Discuss get(), item(), keys() and values() Dictionary methods in python with examples.
(Jan/Feb 2021 – 8M)
6. Create a function to print out a blank tic-tac-toe board. (Jan/Feb 2021 – 7M)
7. Develop a program to accept a sentence from the user and display the longest word of that
sentence along with its length. (Jan/Feb 2021 – 6M)
8. What is List? Explain the concept of List Slicing with example. (July/August 2022 – 6M)
9. What is Dictionary? How it is different from list? Write s program to count the number of
occurrences of character in a string. (July/August 2022 – 7M)
10. Write a python program that accepts a sentence and find the number of words, digits,
uppercase letters and lowercase letters. (July/August 2022 – 7M)
11. What is a List? Explain the methods that are used to delete items from the List. (Feb / Mar
2022 – 8M)
12. Write a program to take a sentence as input and display the longest word in the given
sentence. (Feb / Mar 2022 – 6M)
13. How is Dictionary different from list? Assume a Dictionary containing city and population
as key and value respectively. Write a program to traverse the dictionary and display most
populous city. (Feb / Mar 2022 – 6M)
14. Write a program to create a list of number and display the count of even and odd numbers
in the lsit. (Feb / Mar 2022 – 6M)
---------------------- ALL THE BEST -------------------------
Dept of CSE(IOT), Sir MVIT 32