0% found this document useful (0 votes)
723 views

BPLCK105B Module 2 Notes

Uploaded by

saykrishna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
723 views

BPLCK105B Module 2 Notes

Uploaded by

saykrishna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

Module 2

Lists, Dictionaries and Structuring Data, Manipulating Strings

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

Textbook 1: Chapters 4 – 6 RBT: L1, L2, L3

Textbook 1: Al Sweigart, “Automate the Boring Stuff with Python”, 1st Edition, No Starch Press,
2015. (Available under CC-BY-NC-SA license at https://automatetheboringstuff.com/)

2.1. The List Data Type


• A list can be defined as a collection of values or items of same or different types.
• The items in the list are separated with the comma (,) and enclosed with the square brackets [].
• A list is a value that contains multiple values in an ordered sequence.
• A list is mutable (new, deleted, modify).
• The values in list are called elements or sometimes items.
• The value [] is an empty list that contains no values, similar to '', the empty string.
• A list can be defined as follows.
L1 = ["Raju", 102, "India"] #Creates list ['Raju', 102, 'India']
L2 = [1, 2, 3, 4, 5, 6] #Creates List [1, 2, 3, 4, 5, 6]
L3 = [ ] #Creates List L3 with no items
spam = ['cat', 'bat', 'rat', 'elephant']

 A list can be displayed as follows.


print(L1) #displays ['Raju', 102, 'India']
print(L2) #displays [1, 2, 3, 4, 5, 6]

Department of CSE, Vemana IT Page 1 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

print(L3) #displays [ ]
print(spam) #displays ['cat', 'bat', 'rat', 'elephant']

Getting Individual Values in a List with Indexes


• To access values in lists, use the square brackets for slicing along with the index or indices to
obtain value available at that index.
• The integer inside the square brackets that follows the list is called an index.
• The first value in the list is at index 0, the second value is at index 1, the third value is at index 2,
and so on.

>>> spam = ['cat', 'bat', 'rat', 'elephant']


>>> spam #['cat', 'bat', 'rat', 'elephant']
>>> spam[0] #'cat'
>>> spam[1] #'bat'
>>> spam[2] #'rat'
>>> spam[3] #'elephant‘
>>> spam[1.0] #TypeError: list indices must be integers
>>> spam[int(1.0)] #’bat’
>>> spam[4] #IndexError: list index out of range
>>> 'Hello ' + spam[2] #'Hello rat‘
>>> 'The ' + spam[0] + ' ate ' + spam[2] #'The cat ate rat'

• Lists can also contain other list values. The values in these lists of lists can be accessed using
multiple indexes.
• The first index dictates which list value to use, and the second indicates the value within the list
value.
>>> spam = [['cat', 'bat'], [10, 20, 30, 40, 50]]
>>> spam #[['cat', 'bat'], [10, 20, 30, 40, 50]]
>>> spam[0][1] #'bat'
>>> spam[1][4] #50
>>> spam[2][0] #IndexError: list index out of range
>>> spam[1][5] #Index Error

Department of CSE, Vemana IT Page 2 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

Negative Indexes
• Indexes start at 0 and go up, we 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.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[-1] #'elephant'
>>> spam[-3] #'bat'
>>> spam[3] #elephant
• Indexes start at 0 and go up, we 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.
>>> 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.'

Getting Sublists with Slices


• 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 2 integers separated by a colon.
• The difference between indexes and slices.
o spam[2] is a list with an index (one integer).
o spam[1:4] is a list with a slice (two integers).
o In a slice, the first integer is the index where the slice starts (including) and second integer is
the index where the slice ends (Excluding) and evaluates to a new list value

>>> spam = ['cat', 'bat', 'rat', 'elephant']


>>> spam[0:4] #['cat', 'bat', 'rat', 'elephant']
>>> spam[1:3] #['bat', 'rat']
>>> spam[0:-1] #['cat', 'bat', 'rat']
>>> spam[::-1] #['elephant', 'rat', 'bat', 'cat']

Department of CSE, Vemana IT Page 3 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

 We 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 and Leaving out the second index is same as
using the length of the list.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[:2] #['cat', 'bat'] prints elements of pos 0 and 1
>>> spam[1:] #['bat', 'rat', 'elephant'] prints all excluding 0
>>> spam[:] #['cat', 'bat', 'rat', 'elephant'] prints all

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, just like it
can count the number of characters in a string value.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> len(spam)

Changing Values in a List with Indexes


 When the bracket operator appears on the left side of an assignment, it identifies the element of
the list that will be assigned.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[1] = 'aardvark‘ #pos 1 bat value is changed to aardvark
>>> spam #['cat', 'aardvark', 'rat', 'elephant']
>>> spam[2]=spam[1] # pos 1 value is assigned to pos 2
>>> spam #['cat', 'aardvark', 'aardvark', 'elephant']
>>> spam[-1] = 12345 #last pos vaue is changed to 12345
>>> spam #['cat', 'aardvark', 'aardvark', 12345]

 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.
>>> [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']

Department of CSE, Vemana IT Page 4 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

 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.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> del spam[2] #deletes element at pos 2
>>> spam #['cat', 'bat', 'elephant']
>>> del spam[2] #deletes element at pos 2
>>> spam #['cat', 'bat']

Insertion of elements into LIST


 append: list1.append(10) #insert ele at last pos
 insert: list1.insert(1,23) #insert 23 in pos 1
 list1.insert(-1,20) #insert 20 into lastpos-1
 If index is not available to insert, item will be inserted at last pos

Removing Values from Lists with del Statements


The del statement can also be used on a simple variable to delete it, as if it were an “unassignment”
statement.
If you try to use the variable after deleting it, you will get a NameError error because the variable no
longer exists.
>>> del spam #deletes all elements in spam list
>>> spam #NameError: name 'spam' is not defined

2.2. Working with Lists


 Advantages of using lists : lists program will become much more flexible in processing data than
it would be with several repetitive variables.
catnames = []
while True:
print('Enter name of cat'+str(len(catnames)+1) + 'or q to stop')
name = input()
if name == 'q' :
break
catnames = catnames + [name] # list concatenation

Department of CSE, Vemana IT Page 5 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

print('The cat names are:')


for name in catnames:
print(name)

Output:
Enter name of cat1or q to stop: candy
The cat names are: candy
Enter name of cat2or q to stop: arjun
The cat names are: candy arjun
Enter name of cat3or q to stop: q

Using for Loops with Lists


 A for loop repeats the code block once for each value in a list or list-like value.
for i in range(4): # accepts 0 to 4
print(i) #outputs 01234
is same as
for i in [0, 1, 2, 3]:
print(i) #outputs 01234

supplies = ['pens', 'staplers', 'flame-throwers', 'binders']


for i in range(len(supplies)): # 0 to 3
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: flame-throwers
Index 3 in supplies is: binders

The in and not in 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.
To determine whether a value is or isn’t in a list by using in and not in operators.

Department of CSE, Vemana IT Page 6 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

These expressions will evaluate to a Boolean value


>>> 'hello' in ['hello', 'hi', 'how', 'are','you'] #True
>>> spam=['hello', 'hi', 'how', 'are','you']
>>> 'cat' in spam #False
>>> 'howdy' not in spam #True
>>> 'cat' not in spam #True
>>> 'how' not in spam #False

myFruits = ['Apple', 'Orange', 'Banana']


print('Enter a Fruit name:')
name = input() #read name from user
if name not in myFruits:
print('I do not have a Fruit named ' + name + ' in my List')
else:
print(name + ' is in my Fruit List.')

The Multiple Assignment Trick


 The multiple assignment trick is a shortcut that allows us to assign multiple variables with the
values in a list in one line of code
Normal Way
>>> cat = ['fat', 'black', 'loud']
>>> size = cat[0]
>>> color = cat[1]
>>> color = cat[1]
>>> disposition = cat[2]
>>> size #'fat'
>>> color #'black'
>>> disposition #'loud'
>>> cat = ['fat', 'black', 'loud']
>>> size, color, disposition= cat
>>> size,color,disposition #('fat', 'black', 'loud')

Department of CSE, Vemana IT Page 7 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

 The number of variables and the length of the list must be exactly equal, or Python will give you
a ValueError:
>>> size, color, disposition, name = cat
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
size, color, disposition, name = cat
ValueError: not enough values to unpack (expected 4, got 3)

2.3. Augmented Assignment Operators


 When assigning a value to a variable, you will frequently use the variable itself.
>>> spam = 42
>>> spam = spam + 1
>>> spam #43
 As a shortcut, you can use the augmented assignment operator += to do the same thing:
>>> spam = 42
>>> spam += 1 #spam = spam + 1
>>> spam #43

 The += operator can also do string and list concatenation, and the *= operator can do string and
list replication.
>>> fruits='Apple'
>>> fruits+=' Banana'
>>> fruits+=' Mango'
>>> fruits #'Apple Banana Mango‘

Department of CSE, Vemana IT Page 8 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

>>> fruits=['Apple']
>>> fruits *=3 #fruits*3
>>> fruits #['Apple', 'Apple', 'Apple']

2.4. Methods
Methods: Finding a Value in a List with the index() Method
 A method is the same thing as a function, except it is “called on” a value.
 Each data type has its own set of methods.
 List values have an index() method that can be passed a value, and if that value exists in the list,
the index of the value is returned. If the value isn’t in the list, then Python produces a ValueError
error.
>>> spam = ['hello', 'hi', 'how', 'are','you']
>>> spam.index('hello') #0
>>> spam.index('how') #2
>>> spam.index('hello hi') #'hello hi' is not in list
 When there are duplicates of the value in the list, the index of its first appearance is returned.
>>> spam = ['hello', 'hi', 'how', 'are','hello','you']
>>> spam.index('hello') #0

Adding Values to Lists with the append() and insert() Methods


 To add new values to a list, use the append() and insert() methods.
 The append() method call adds the argument to the end of the list.
 The insert() method can insert a value at any index in the list.
>>> fruits=['Apple','Mango','Orange']
>>> fruits # ['Apple', 'Mango', 'Orange']
>>> fruits.append('Grapes')
>>> fruits #['Apple', 'Mango', 'Orange', 'Grapes']
>>> fruits=['Apple','Mango','Orange']
>>> fruits # ['Apple', 'Mango', 'Orange']
>>> fruits.insert(1,'Grapes')
>>> fruits #['Apple', 'Grapes', 'Mango', 'Orange']

Department of CSE, Vemana IT Page 9 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

 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.

append() and insert() on List


>>> fruits=['Apple']
>>> fruits #['Apple']
>>> fruits.append('Mango')
>>> fruits #['Apple', 'Mango']

append() and insert() on String


>>> fruits='Apple'
>>> fruits.append('Mango') #AttributeError: ‘int' object has no
attribute 'append'

append() and insert() on integer


>>> num=42
>>> num.insert(1,23) #AttributeError: ‘int' object has no attribute 'append'

Removing Values from Lists with remove()


 The remove() method is passed the value to be removed from the list it is called on.
>>> fruits=['Apple', 'Grapes', 'Mango', 'Orange']
>>> fruits.remove('Mango')
>>> fruits #['Apple', 'Grapes', 'Orange']

 Attempting to delete a value that does not exist in the list will result in a ValueError error.
>>> fruits=['Apple', 'Grapes', 'Mango', 'Orange']
>>> fruits.remove('Pineapple') #ValueError: list.remove(x): x not in list

 If the value appears multiple times in the list, only the first instance of the value will be removed.
>>> fruits=['Apple', 'Grapes','Apple', 'Grapes', 'Mango', 'Orange']
>>> fruits #['Apple', 'Grapes', 'Apple', 'Grapes', 'Mango', 'Orange']
>>> fruits.remove('Grapes')

Department of CSE, Vemana IT Page 10 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

>>> fruits #['Apple', 'Apple', 'Grapes', 'Mango', 'Orange']


 The del statement is good to use when you know the index of the value you want to remove from
the list. The remove() method is good when you know the value you want to remove from the list.

Sorting the Values in a List with the sort() Method


 Lists of number values or lists of strings can be sorted with the sort() method.
>>> spam = [2, 5, 3.14, 1, -7]
>>> spam.sort()
>>> spam #[-7, 1, 2, 3.14, 5]
>>> spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants']
>>> spam #['ants', 'cats', 'dogs', 'badgers', 'elephants']
>>> spam.sort()
>>> spam #['ants', 'badgers', 'cats', 'dogs', 'elephants']
 To sort the values in reverse order, pass True for the reverse keyword argument to have sort()
function
>>> spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants']
>>> spam.sort(reverse=True)
>>> spam #['elephants', 'dogs', 'cats', 'badgers', 'ants']

 sort() function cannot sort lists that have both number values and string values in them, since
Python doesn’t know how to compare these values.
>>> spam = [1, 3, 2, 4, 'Alice', 'Bob']
>>> spam.sort() #TypeError: '<' not supported between instances of 'str' and 'int'
sort() uses “ASCIIbetical order” rather than actual alphabetical order for sorting
strings. This means uppercase letters come before lowercase letters. Therefore,
the lowercase a is sorted so that it comes after the uppercase Z.

>>> spam = ['Alice', 'ants', 'Bob', 'badgers', 'Carol', 'cats']


>>> spam.sort()
>>> spam #['Alice', 'Bob', 'Carol', 'ants', 'badgers', 'cats']

Department of CSE, Vemana IT Page 11 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

 If you need to sort the values in regular alphabetical order, pass str. lower for the key keyword
argument in the sort() method call.
>>> spam = ['a', 'z', 'A', 'Z']
>>> spam.sort(key=str.lower)
>>> spam #['a', 'A', 'z', 'Z']

2.5. Example Program: Magic 8 Ball


 Using lists, you can write a much more elegant version of the Magic 8 Ball program. Instead of
several lines of nearly identical elif statements, you can create a single list that the code works
with.
 Open a new file editor window and enter the following code.
import random
messages = ['It is certain',
'It is decidedly so',
'Yes definitely',
'Reply hazy try again',
'Ask again later',
'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

 When you run this program, you’ll see that it works the same as the previous magic8Ball.py
program.
 Notice the expression you use as the index into messages: random.randint(0, len(messages) - 1).
 This produces a random number to use for the index, regardless of the size of messages. That is,
you’ll get a random number between 0 and the value of len(messages) - 1.
 The benefit of this approach is that you can easily add and remove strings to the messages list
without changing other lines of code.
 If you later update your code, there will be fewer lines you have to change and fewer chances for
you to introduce bugs.

Department of CSE, Vemana IT Page 12 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

2.6. 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
import random
messages = ['It is certain', 'It is decidedly so', 'Yes definitely',
'Reply hazy try again', 'Ask again later', '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
Concentrate and ask again
My reply is no

 Example
>>> name='Apple‘
>>> name[0] #'A'
>>> name[-2] #'l'
>>> name[0:4] #'Appl'
>>> 'Ap' in name #True
>>> 'p' not in name #False
>>> for i in name:
print('* * *' + i + '* * *')
 Output
* * *A* * *
* * *p* * *
* * *p* * *
* * *l* * *
* * *e* * *

Department of CSE, Vemana IT Page 13 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

Mutable and Immutable Data Types


 A list value is a mutable data type: It can have values added, removed, or changed. However, a
string is immutable: It cannot be changed. Trying to reassign a single character in a string
results in a TypeError error.
>>> name='Hello how are you?‘
>>> name[2]='P‘ #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="Apple is the fruit“
>>> name #'Apple is the fruit‘
>>> new_name=name[0:8] + ' a ' + name[13:18]
>>> new_name #'Apple is a fruit'

List is Mutable
>>> eggs=[1,2,3]
>>> eggs #[1, 2, 3]
>>> eggs=[4,5,6]
>>> eggs #[4, 5, 6]
 The list value in eggs isn’t being changed here; rather, an entirely new and different list value ([4,
5, 6]) is overwriting the old list value ([1, 2, 3]).

Mutable and Immutable Data Types


If you wanted to actually modify the original list, then
>>> eggs = [1, 2, 3]
>>> eggs #[1, 2, 3]
>>> eggs[0]=5 #Modify position 0 value to 5
>>> eggs #[5, 2, 3]
>>> del eggs[2] #delete a value from position 2
>>> eggs #[5, 2]
>>> eggs.append(6) #insert value 6 to end of list
>>> eggs #[5, 2, 6]

Department of CSE, Vemana IT Page 14 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

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 ].
 Second, Tuples are immutable (cannot have their values modified, appended, or removed).
>>> eggs=('Apple', 1, 2, 3)
>>> eggs #('Apple', 1, 2, 3)
>>> type(eggs) #<class 'tuple'>
>>> eggs[0]=0
Traceback (most recent call last):
File "<pyshell#28>", line 1, in <module>
eggs[0]=0
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. Otherwise, Python will treat as normal data type values.

>>> eggs1=(2)
>>> eggs1 #2
>>> type(eggs1) #<class 'int'>
>>> type(('hello')) #<class 'str'>

>>> eggs2=(2,)
>>> eggs2 #(2,)
>>> type(eggs2) #<class 'tuple'>
>>> type(('hello',)) #<class 'tuple'>

Converting Types with the list() and tuple() Functions


>>> list1=[1,2,3,4]
>>> tup1=tuple(list1) #converts list to tuple
>>> tup1 #(1, 2, 3, 4)
>>> list(('cat', 'dog', 5)) #['cat', 'dog', 5]
>>> list2=list(('cat', 'dog', 5))
>>> list2 #['cat', 'dog', 5]

Department of CSE, Vemana IT Page 15 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

>>> list3=list('hello')
>>> list3 #['h', 'e', 'l', 'l', 'o']

2.7. References
 Variables store strings and integer values
>>> spam=42
>>> cheese=spam
>>> spam=100
>>> spam #100
>>> cheese #42
 When you assign a list to a variable, you are actually assigning a list reference to the variable. A
reference is a value that points to some bit of data, and a list reference is a value that points to a
list.
>>> spam = [0, 1, 2, 3, 4, 5]
>>> cheese = spam
>>> cheese[1] = 'Hello!'
>>> cheese #[0, 'Hello!', 2, 3, 4, 5]
>>> spam #[0, 'Hello!', 2, 3, 4, 5]

 When you create the list,


1. Assign a reference to list variable.
2. Copies only the list reference, not the list value itself.
3. Modifying the same list affects reference.

Passing References
References are particularly important for understanding how arguments get passed to functions. When a
function is called, the values of the arguments are copied to the parameter variables.
def eggs(Param):
Param.append('Hello')
spam = [1, 2, 3]
eggs(spam)

Department of CSE, Vemana IT Page 16 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

print(spam) #[1, 2, 3, 'Hello']

The copy Module’s copy() and deepcopy() Functions


 If the function modifies the list or dictionary that is passed, these changes will affect the original
list or dictionary value.
 For this, Python provides a module named copy that provides both the copy() and deepcopy()
functions. 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.
>>> import copy
>>> spam = ['A', 'B', 'C', 'D']
>>> cheese=copy.copy(spam)
>>> spam #['A', 'B', 'C', 'D']
>>> cheese #['A', 'B', 'C', 'D']
>>> cheese[0]='Z'
>>> cheese #['Z', 'B', 'C', 'D']
>>> spam #['A', 'B', 'C', 'D']
>>> spam[3]='X‘
>>> spam #['A', 'B', 'C', 'X']
>>> cheese #['Z', 'B', 'C', 'D']

 If the function modifies the list or dictionary that is passed, these changes will affect the original
list or dictionary value.
 For this, Python provides a module named copy that provides both the copy() and deepcopy()
functions.
 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.
 Deep copy is a process in which the copying process occurs recursively. In case of deep copy, a
copy of object is copied in other object.
 Any changes made to a copy of object do not reflect in the original object. In python, this is
implemented using “deepcopy()” function.

Department of CSE, Vemana IT Page 17 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

The copy Module’s copy() and deepcopy() Functions


# importing copy module
import copy
list1 = [1, 2, [3,5], 4]
list2 = copy.copy(list1)
list3 = copy.deepcopy(list1)
print(list1) #[1, 2, [3, 5], 4]
print(list2) #[1, 2, [3, 5], 4]
print(list3) #[1, 2, [3, 5], 4]

2.8. Dictionaries and Structuring Data


 A dictionary is a collection which is unordered, changeable and indexed. Dictionaries are written
with curly brackets { }, and they have keys and values. Indexes for dictionaries are called keys,
and a key with its associated value is called a key-value pair.
 The main difference is that List uses index to access the elements. Dictionary uses keys to access
the elements. The function “ dict “ creates a new dictionary with no items. dict is the name of a
built-in function, avoid using it as a variable name.
>>> d=dict()
>>> print(d) #{}
 Dictionaries can still use integer values as keys, just like lists use integers for indexes, but they
do not have to start at 0 and can be any number.
{51: 'CNS', 52: 'CG', 53: 'DBMS', 54: 'ATC', 55: 'ADP'}

Create and print Dictionary


d={
"brand": "toyota",
"model": "etios liva",
"year": 2011
}

print(d)
or

Department of CSE, Vemana IT Page 18 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

d = { "brand": "toyota", "model": "etios liva", "year": 2011 }


print(d)

Dictionaries vs. Lists

LIST DICTIONARY

List is a collection of index values pairs as that Dictionary is a hashed structure of key and
of array in c++. value pairs.

Dictionary is created by placing elements in {


List is created by placing elements in [ ]
} as “key”:”value”, each key value pair is
seperated by commas “, “
seperated by commas “, ”

The indices of list are integers starting from 0. The keys of dictionary can be of any data type.

The elements are accessed via indices. The elements are accessed via key-values.

The order of the elements entered are


There is no guarantee for maintaining order.
maintained.

 Items in dictionaries are unordered. First element in the list would be at index 0. But, no first
item in dictionary. Dictionaries are not ordered, they can’t be sliced like lists.
>>> spam = ['cats', 'dogs', 'moose']
>>> bacon = ['dogs', 'moose', 'cats']
>>> spam == bacon #False
>>> eggs = {'name': 'Zophie', 'species': 'cat', 'age': '8'}
>>> ham = {'species': 'cat', 'age': '8', 'name': 'Zophie'}
>>> eggs == ham
 Though dictionaries are not ordered, the fact that you can have arbitrary values for the keys allows
you to organize your data in powerful ways. Example: program to store data about birthdays using
a dictionary with the names as keys and the birthdays as values.

birthdays = {'Raju': 'Apr 19', 'Manu': 'Jul 12', 'Anup': 'Jul 9'}
while True:
print('Enter a name: (blank to quit)')
name = input()

Department of CSE, Vemana IT Page 19 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

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.')

The keys(), values(), and items() Methods


 There are three dictionary methods that will return 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 (dict_keys, dict_values, and dict_items, respectively) can be used in for loops.
 A for loop iterates over each of the values in the spam dictionary
 Example
spam = {'color': 'red', 'age': 42}
for v in spam.values():
print(v) #red 42
for v in spam.keys():
print(v) #color age

 A for loop can also iterate over the keys or both keys and values:
spam = {'color': 'red', 'age': 42}
for k in spam.keys():
print(spam[k]) # red 42
for i in spam.items():
print(i) #('color', 'red') ('age', 42)

Department of CSE, Vemana IT Page 20 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

 Using the keys(), values(), and items() methods, a for loop can iterate over the keys, values, or
key-value pairs in a dictionary. The values in the dict_items value returned by the items() method
are tuples of the key and value.
spam = {'color': 'red', 'age': 42}
for k in spam.keys():
print(spam[k]) # red 42
for i in spam.items():
print(i) #('color', 'red') ('age', 42)
 The get() method returns the value of the item with the specified key.
Syntax: dictionaryname.get(keyname, value)
Parameter Values
Keyname Required The keyname of the item you want to return the value from
value  Optional  A value to return if the specified key does not exist. Default value
None

The get() Method


 Items in the dictionary can be accessed by referring to its key name, inside square brackets. Get
the value of the "model" key:
>>> d = { "brand": "toyota", "model": "etios liva", "year": 2011 }
>>> x = d["model“] here, model is key
>>> print(x) #etios liva
 There is also a method called get() that will give you the same result:
 Get the value of the "model" key:
>>> x = d.get("model")
car = { "brand": "toyota", "model": "etios liva", "year": 2011 }
y=car.get("year") #2011
c=car.get("color") #nothing
c1=car.get("color”,2020) #2020
print(y) #2011
print(c) #None
print(c1) #2020
print(car) #{'brand': 'toyota', 'model': 'etios liva', 'year': 2011}

Department of CSE, Vemana IT Page 21 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

>>> car={'brand': 'toyota', 'model': 'etios liva', 'year': 2011}


>>> 'I bought '+str(car.get('brand',0)) + ' car ' +str(car.get('model',0)) + ' model ' + 'in the year '
+ str(car.get('year‘,2000))

Output: 'I bought toyota car etios liva model in the year 2011‘

 If no key in the dictionary, the default value 0 is returned by the get() method. If no get method is
used and no key present in dictionary, then ERROR will be raised.
>>> car={'brand': 'toyota', 'model': 'etios liva', 'year': 2011}
>>> I bought '+str(car['brand']) + ' color: ' + str(car['color'])
Output: KeyError: 'color'

The setdefault() Method


 To set a value in a dictionary for a certain key only if that key does not already have a value, then
setdefault() method is used.

General Way
fruits = {'name': 'Apple', 'cost': 90}
if 'color' not in fruits:
fruits['color'] = 'green'
print(fruits)

Using setdeault
fruits = {'name': 'Apple', 'cost': 90}
fruits.setdefault('color', 'black')
print(fruits)

Output:{'name': 'Apple', 'cost': 90, 'color': 'black'}

Using setdeault
fruits = {'name': 'Apple', 'cost': 90,'color': 'Red'}
print(fruits)

Department of CSE, Vemana IT Page 22 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

fruits.setdefault('color', 'green')
print(fruits)

Output: {'name': 'Apple', 'cost': 90, 'color': 'Red'}

 The setdefault() method is a nice shortcut to ensure that a key exists. Here is a short program that
counts the number of occurrences of each letter in a string.
 Example
message = 'Application Development using Python Programming'
count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
print(count)
#{'A': 1, 'p': 3, 'l': 2, 'i': 4, 'c': 1, 'a': 2, 't': 3, 'o': 4, 'n': 5, ' ': 4, 'D': 1, 'e': 3, 'v': 1, 'm': 3, 'u': 1, 's': 1,
'g': 3, 'P': 2, 'y': 1, 'h': 1, 'r': 2}

 The program loops over each character in the message variable’s string, counting how often each
character appears. The setdefault() method call ensures that the key is in the count dictionary (with
a default value of 0) so the program doesn’t throw a KeyError error when count[character] =
count[character] + 1 is executed.

2.9. Pretty Printing


 Using pprint module have access to the pprint() and pformat() functions that will “pretty print” a
dictionary’s values. This is helpful when you want a cleaner display of the items in a dictionary
than what print() provides.
 Example
import pprint
message = 'Application Development using Python Programming.'
count = {}
for character in message:
count.setdefault(character, 0)

Department of CSE, Vemana IT Page 23 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

count[character] = count[character] + 1
pprint.pprint(count)
 The pprint.pprint() function is especially helpful when the dictionary itself contains nested lists or
dictionaries.

2.10. Using Data Structures to Model Real-World Things


In algebraic chess notation, the spaces on the chessboard are identified by a number and letter coordinate

A Tic-Tac-Toe Board
 A tic-tac-toe board looks like a large hash symbol (#) with nine slots that can each contain an X,
an O, or a blank.
 To represent the board with a dictionary, you can assign each slot a string-value key. String values
'X', 'O', or ' ' (a space character) are used in each slot on the board which needs to store nine strings.
So, dictionary can be used. The string value with the key 'top-R' can represent the top-right corner,
the string value with the key 'low-L' can represent the bottom-left corner, the string value with the
key 'mid-M' can represent the middle, and so on.

Department of CSE, Vemana IT Page 24 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

The slots of a tic-tactoe board with their corresponding keys


 This dictionary is a data structure that represents a tic-tac-toe board. Store this board-as-a
dictionary in a variable named theBoard. Open a new file editor window, and enter the following
source code, saving it as ticTacToe.py:

theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ', 'mid-L': ' ', 'mid-M': ' ', 'mid-R': ' ', 'low-L': '
', 'low-M': ' ', 'low-R': ' '}

An empty tic-tac-toe board


theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ', 'mid-L': ' ', 'mid-M': 'X', 'mid-R': ' ','low-L':
' ', 'low-M': ' ', 'low-R': ' '}

The First Move

Department of CSE, Vemana IT Page 25 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

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'}

Player O wins

create a function to print the board dictionary onto the screen.


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'])

printBoard(theBoard)

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'])

Department of CSE, Vemana IT Page 26 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

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)

Nested Dictionaries and Lists


 In Python, a nested dictionary is a dictionary inside a dictionary. It's a collection of dictionaries
into one single dictionary.
nested_dict = { 'dictA': {'key_1': 'value_1'},
'dictB': {'key_2': 'value_2'}}
 Here, the nested_dict is a nested dictionary with the dictionary dictA and dictB. They are two
dictionary each having own key and value.
 To access element of a nested dictionary, we use indexing [] syntax in Python.
people = {1: {'name': 'Raju', 'age': '36', 'sex': 'Male'}, 2: {'name': 'Manu', 'age': '8', 'sex': 'Male'}}
print(people[1]['name']) #Raju
print(people[1]['age']) #36
print(people[1]['sex']) #Male
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():

Department of CSE, Vemana IT Page 27 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

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')))

 Number of things being brought:


- Apples 7
- Cups 3
- Cakes 0
- Ham Sandwiches 3
- Apple Pies 1

Dictionary: Change Values


You can change the value of a specific item by referring to its key name:
>>> d = {"brand": "toyota", "model": "etios liva", "year": 2011 }
>>> d["year"] = 2018 #
>>> print(d) # {'brand': 'toyota', 'model': 'etios liva', 'year': 2018

Loop Through a Dictionary


 Looping through a dictionary is done by using a for loop. To print all key names in the
dictionary, one by one:

for x in d:
print(x) # brand model year

 To print all values in the dictionary, one by one:


for x in d:
print(d[x]) # Toyota etios liva 2018

 You can also use the values() function to return values of a dictionary:

Department of CSE, Vemana IT Page 28 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

for x in d.values():
print(x) # Toyota etios liva 2018

 items() function is used to loop through both keys and values


for x,y in d.items():
print(x,y) #brand Toyota model etios liva year 2018

Dictionary: Check if Key Exists


 To determine if a specified key is present in a dictionary use the in keyword: Check if "model" is
present in the dictionary:
d = { "brand": "toyota", "model": "etios liva", "year": 2011 }
if "model" in d:
print("Yes, 'model' is one of the keys in the dictionary d")

 To determine how many items (key-value pairs) a dictionary has, use the len() method.
 Example: Print the number of items in the dictionary:
d = { "brand": "toyota", "model": "etios liva", "year": 2011 }
print(len(d))

 Adding an item to the dictionary is done by using a new index key and assigning a value to it:
d = { "brand": "toyota", "model": "etios liva", "year": 2011 }
d["color"] = "White"
print(d)
#{'brand': 'Toyota', 'model': 'Etios liva', 'year': 2011, 'color': 'White'}

Removing Items: pop()


 The pop() method removes the item with the specified key name:
d = {"brand": "toyota", "model": "etios liva", "year": 2011 }
d.pop("model")
print(d) # {'brand': 'Toyota', 'year': 2011}

Removing Items: popitem()


 The popitem() method removes the last inserted item (in versions before 3.7, a random item is
removed instead):

Department of CSE, Vemana IT Page 29 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

d = {"brand": "toyota", "model": "etios liva", "year": 2011 }


d.popitem()
print(d) # {'brand': 'Toyota', 'model': 'Etios liva'}

Removing Items: del keyword


 The del keyword removes the item with the specified key name:
d = {"brand": "toyota", "model": "etios liva", "year": 2011 }
del d["model"]
print(d) #{'brand': 'Toyota', 'year': 2011}

 The del keyword can also delete the dictionary completely:


d = {"brand": "toyota", "model": "etios liva", "year": 2011 }
del d
print(d) #this will cause an error because "d" no longer exists.

Removing Items: clear()


 The clear() method empties the dictionary:
d = {"brand": "toyota", "model": "etios liva", "year": 2011 }
d.clear()
print(d) #{ } empty dictionary but retains structure

Copy a Dictionary
 Cannot copy a dictionary using dict2 = dict1, because: dict2 will only be a reference to dict1, and
changes made in dict1 will automatically reflects in dict2.
 To make a copy, use the built-in Dictionary method copy().
d = {"brand": "toyota", "model": "etios liva", "year": 2011 }
myd = d.copy()
print(myd)
# {'brand': 'Toyota', 'model': 'Etios liva', 'year': 2011}

Dictionary as a set of counters


word = 'Welcome'
d = dict()
for c in word:

Department of CSE, Vemana IT Page 30 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

if c not in d:
d[c] = 1
else:
d[c] = d[c] + 1
print(d)
# {'W': 1, 'e': 2, 'l': 1, 'c': 1, 'o': 1, 'm': 1}

 Dictionaries have a method called “get” that takes a key and a default value. If the key appears in
the dictionary, get returns the corresponding value; otherwise it returns the default value.
 For example:
d = {"brand": "toyota", "model": "etios liva", "year": 2011 }
print(d.get('year', 0)) #or print(d.get('year')) #2011
print(d.get('color', 0)) #0
print(d.get('color', 'white')) #white

 The get method automatically handles the case where a key is not in a dictionary, we can reduce
four lines down to one and eliminate the if statement.
word = 'welcome'
d = dict()
for c in word:
d[c] = d.get(c,0) + 1
print(d) # {'w': 1, 'e': 2, 'l': 1, 'c': 1, 'o': 1, 'm': 1}
 If you use a dictionary as the sequence in a for statement, it traverses the keys of the dictionary.
This loop prints each key and the corresponding value:
d = {"brand": "Toyota", "model": "Etios liva", "year": 2011}
for key in d:
print(key, d[key]) #brand Toyota model Etios liva year 2011

Looping and dictionaries


 If you use a dictionary as the sequence in a for statement, it traverses the keys of the dictionary.
This loop prints each key and the corresponding value:
d = {"brand": "Toyota", "model": "Etios liva", "year": 2011}
for key in d:

Department of CSE, Vemana IT Page 31 of 44


Introduction to Python Programming (22PLC15B) Module 2: Lists, Dictionaries and Structuring Data, Manipulating Strings

print(key, d[key]) #brand Toyota model Etios liva year 2011

 Example: if we wanted to find all the entries in a dictionary with a value above ten, we could
write the following code:
counts = { 'chuck' : 1 , 'annie' : 42, 'jan': 100}
for key in counts:
if counts[key] > 10 :
print(key, counts[key]) # annie 42 jan 100

 To print the keys in alphabetical order


counts = { 'chuck' : 1 , 'annie' : 42, 'jan': 100}
lst = list(counts.keys())
print(lst) #['chuck', 'annie', 'jan']
lst.sort()
for key in lst:
print(key, counts[key]) # annie 42 chuck 1 jan 100

Department of CSE, Vemana IT Page 32 of 44

You might also like