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

module2-python

Python notes about lists functions dictionary and tuple it gives the proper definition of lists tuple and functions

Uploaded by

yashaswini0005
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

module2-python

Python notes about lists functions dictionary and tuple it gives the proper definition of lists tuple and functions

Uploaded by

yashaswini0005
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

Introduction to

Dr. SURESHA V Python


Programming
Code: BPLCK105B/205B

A Simplified Notes As per VTU Syllabus


2022 Scheme

MODULE 2
Python Data Structures:
Lists, Tuples and Dictionaries

Professor
Dept. of E&CE
K.V.G. College of Engineering, Sullia, D.K-574 327
Affiliated to Visvesvaraya Technological University
Belagavi - 590018
Introduction to Python Programming(BPLCK105B) - Module 2: Data Structures- Lists, Tuples and Dictionaries

MODULE 2
Python Data Structures: Lists, Tuples and Dictionaries
Learning Outcomes
After reading this Module, the student will be able to:
o Gain a solid understanding of Python's core data structures: lists, tuples, and
dictionaries.
o Know when and why to use each data structure based on its properties and
performance characteristics.
o Create and manipulate lists effectively, understanding how to use various list
methods and functions.
o Create and utilise tuples in Python programs and Combine lists, tuples, and
dictionaries to solve complex programming problems.
o Write Python programs utilising these data structures to store, access, and
manipulate data efficiently.
o Develop algorithms that effectively use Python data structures to solve real-
world problems.

 Chapter 4: Lists (Textbook 1: Page 80-100): The List Data Type, Working with
Lists Strings. List-like Types: Strings and Tuples.
 Chapter 5: Dictionaries and Structuring Data ((Textbook 1: Page 106-117):
The Dictionary Data Type Using Data Structures to Model Real-World Things.

 Web links (e-Resources):


1. https://www.w3schools.com/python/
2. https://www.javapoint.org/python-programming-language/
Chapter 4: Lists
 Introduction: The following chart provides some built-in data types in Python

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 1


Introduction to Python Programming(BPLCK105B) - Module 2: Data Structures- Lists, Tuples and Dictionaries

4.1 Lists: *** (Jan 24-6M)


o Lists are built-in data types in Python.
o Lists are used to store multiple values in a single variable.
o A list is a value that contains multiple values in an ordered sequence.
o Values inside the list are also called elements or items and are separated with
commas.
o Lists are created using square brackets. Example : ['cat', 'bat', 'rat', 'elephant'].

 List Items: Data types


o List items can be of any data type: String, int, float or boolean data types etc.
Example shown bleow

o A list can contain different data types: Example shown below

 Getting Individual Values in a List with Indexes


o List values that are ordered, changeable, and allow duplicate values.
o List items are indexed, the first item has index [0], the second item has
index [1] etc.
o List items are indexed and can access them by referring to the index number.
o For example consider the list ['cat', 'bat', 'rat', 'elephant'] stored in a variable
named spam.

o The Python code spam[0] would evaluate to 'cat', and spam[1] would evaluate
to 'bat', and so on.
o For example, type the following expressions into the interactive shell.

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 2


Introduction to Python Programming(BPLCK105B) - Module 2: Data Structures- Lists, Tuples and Dictionaries

 Indexing Error: There are two types of errors that occur when there is incorrect
syntax in indexing
1. IndexError: If an index exceeds the number of values in the list value, then
Python gives IndexError. Example

2. TypeError: Indexes can be only integer values, not floats. The following
example will cause a TypeError error:

 Multiple indexing: Lists can also contain other list values. The values in these lists
of lists can be accessed using multiple indexes. See the example below

o The first index dictates which list value to use, and the 2nd indicates the value
within the list value. Ex, spam[0][1] prints 'bat', the 2nd value in the 1st list.
 Negative Indexes: (July 24-8M)
Negative indexing means starting from the end. -1 refers to the last item, -2 refers to
the second last item etc. For example

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 3


Introduction to Python Programming(BPLCK105B) - Module 2: Data Structures- Lists, Tuples and Dictionaries

4.2 Getting Sublists with Slices: (July 24-8M, Jan 24-6M) )


o An index will get a single value from a list, a slice can get several values from a
list, in the form of a new list.
o A slice is typed between square brackets, like an index, but has two integers
separated by a colon.
o In a slice, the first integer is the index where the slice starts. The second integer
is the index where the slice ends (but will not include the value at the 2nd index).

o As a shortcut, we can leave out one or both of the indexes on either side of the colon
in the slice.

o Leaving out the first index is the same as using 0, or a slice beginning of the list and
leaving out the second index is a slice to the end of the list.

4.3 List Operations: *** Some of the list operations are as follows
1. Getting a List’s Length with len( )
2. Changing Values in a List with Indexes
3. List Concatenation and List Replication
4. Removing Values from Lists with del Statements

1. Getting a List’s Length with len( ):


o Python len() function is an inbuilt function in Python.
o The len() function determines how many items are in a list.
o Example 1

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 4


Introduction to Python Programming(BPLCK105B) - Module 2: Data Structures- Lists, Tuples and Dictionaries

2. Changing Values in a List with Indexes: We can use an index of a list to change
the value at that index. To change the value of a specific item, refer to the index
number. Example 1:

o Example 2:

3. List Concatenation and List Replication:


o 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.
o The * operator can also be used with a list and an integer value to replicate
the list. Example

4. Removing Values from Lists with del Statements:


o 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

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 5


Introduction to Python Programming(BPLCK105B) - Module 2: Data Structures- Lists, Tuples and Dictionaries

4.4 Working with Lists: When you first begin writing programs, it’s tempting to
create many individual variables to store a group of similar values. if I wanted to store
the names of my cats, I might be tempted to write code like this. This is bad way to
write code because it leads to have duplicate code in the program.

o Instead of using multiple, repetitive variables, we can use a single variable that
contains a list value.
o Program:

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 6


Introduction to Python Programming(BPLCK105B) - Module 2: Data Structures- Lists, Tuples and Dictionaries

o The benefit of using a list:


- Data is now in a structure.
- The program is much more flexible in processing the data than it would
be with several repetitive variables.

4.5 Using “ for” Loops with Lists: Python Iterate Over a List via for loop You can
loop through the list items by using a for loop.
- Example 1: Print all items in the list, one by one:
-
Program: thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)

Output: apple
banana
cherry
o for loop repeats the code block once for each value in a list or list-like value.

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 7


Introduction to Python Programming(BPLCK105B) - Module 2: Data Structures- Lists, Tuples and Dictionaries

o A common Python technique is to use range (len(someList)) with a for loop to


iterate over the indexes of a list. For example,

o The code in the loop will access the index (as the variable i), the value at that index
(as supplies[i]) and range(len(supplies)) will iterate through all the indexes of
supplies, no matter how many items it contains.

4.6 The “in” and “not in” Operators: (July 2024-6M)


o in and not in operators are used to determine whether a value is or isn’t in a list.
o These expressions will evaluate to a Boolean value

o The following program lets the user type in a pet name and then checks to see
whether the name is in a list of pets.

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 8


Introduction to Python Programming(BPLCK105B) - Module 2: Data Structures- Lists, Tuples and Dictionaries

4.7 The Multiple Assignment Trick


o The multiple assignment trick is a shortcut that lets you assign multiple variables
with the values in a list in one line of code.

o Instead of a left-side program we could type the right-side program to assign


multiple variables but the number of variables and the length of the list must be
exactly equal, or Python will give you a ValueError:

4.8 Augmented Assignment Operators


o It combines the functioning of the arithmetic or bitwise operator with the
assignment operator.
o Ex: Assume to add 7 to a variable “a” and assign the result back to “a”, then
instead of writing normally as “a = a + 7“, we can use the augmented assignment
operator and write the expression as “a += 7“. For example

o Instead of left-side program we could use right-side program i.e., with the
augmented assignment operator += to do the same thing as a shortcut.
o The Augmented Assignment Operators are listed in the below table:

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 9


Introduction to Python Programming(BPLCK105B) - Module 2: Data Structures- Lists, Tuples and Dictionaries

o The += operator can also do string and list concatenation, while the *= operator
can replicate string and list.

4.9 Methods *** (June 24-8M) (July 24-10M) (Jan 24-8M)


o A method is the same as a function, except it is “called on” a value.
o Each data type has its own set of methods. The list data type, for example, has
several useful methods for finding, adding, removing, and otherwise
manipulating values in a list. Namely
1. Finding a Value in a List with the index() Method
2. Adding Values to Lists with the append() and insert() Methods
3. Removing Values from Lists with remove()
4. Sorting the Values in a List with the sort()and reverse() Methods
5. Counting the no. of the same values in the list count()and pop()

1. Finding a Value in a List with the index() Method:(July 24-8M)


o List values have an index() method that can be passed a value, and if that value
exists in the list, the value's index is returned. If the value isn’t in the list, Python
produces a ValueError error. Example

o When there are duplicates of the value in the list, the index of its first
appearance is returned. Example

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 10


Introduction to Python Programming(BPLCK105B) - Module 2: Data Structures- Lists, Tuples and Dictionaries

2. Adding Values to Lists with the append()/extend() and insert() Methods:


(June 2024-8M,July 24-8M)
o To add new values to a list, use the append( ),extend( ) and insert( ) methods.
o The previous append( ) method call adds the argument to the end of the list.

o The insert( ) method can insert a value at any index in the list. Example shown
below, here chicken is inserted in the index 1.

o The append( ) and insert( ) methods are list methods and can be called only on
list values, not other values such as strings or integers. It shows an attribute
error. Example

3. Removing Values from Lists with remove():(July 24-8M)


o The remove() method is passed the value to be removed from the list it is
called on.

o Attempting to delete a value that does not exist in the list will result in a
ValueError.

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 11


Introduction to Python Programming(BPLCK105B) - Module 2: Data Structures- Lists, Tuples and Dictionaries

o If the value appears multiple times in the list, only the first instance of the
value will be removed.

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

4. Sorting the Values in a List with the sort() and reverse()Method


-(July 2024-8M, Jan 24-6M)
o Lists of number values or lists of strings can be sorted with the sort()
method. The example below shows the sort of the elements in the list in
ascending order

o We can also pass True for the reverse keyword argument to sort( ) the
values in reverse order using reverse( ) methods

o There are THREE things you should note about the sort() method.

First, the sort() method sorts the list in place; don’t try to return value by
writing code like spam = spam.sort().

Second, we cannot sort lists with both number and string values. Example

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 12


Introduction to Python Programming(BPLCK105B) - Module 2: Data Structures- Lists, Tuples and Dictionaries

Third, sort() uses “ASCIIbetical order(upper case)” rather than actual alphabetical
order(lower case) for sorting strings

o If we need to sort the values in regular alphabetical order, pass str. lower for
the key keyword argument in the sort ( ) method call.

5. List count() Method and List pop() method


o The count() method returns the number of elements with the specified value.
o Syntax: list.count(value)
o Example: points = [1, 4, 2, 9, 7, 8, 9, 3, 1]
x = points.count(9)
print(x)
o OUTPUT= 2, it returns the number of times the value 9 appears in the list

o The pop() method removes the element at the specified position in the list

o Syntax:list.pop(pos). pos = number specifying the position of the element you


want to remove

o Example: fruits = ['apple', 'banana', 'cherry']


x = fruits.pop(1)
o OUTPUT=[‘apple’,’ cherry’]

1.5 Example Program: Magic 8 Ball with a List


 About Magic 8 Ball game
o Introduction:
- The Magic 8 Ball is a plastic sphere, made to look like an oversized eight ball,
that is used for fortune-telling or seeking advice.
- A "Magic 8 Ball game" is a novelty toy or app where you ask a yes or no
question, then shake it to reveal a random answer from a set of pre-
determined possibilities.

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 13


Introduction to Python Programming(BPLCK105B) - Module 2: Data Structures- Lists, Tuples and Dictionaries

o Key points about the Magic 8 Ball:


 How to play:

- Ask a yes or no question, shake the ball, and then look through the window
to see the answer.
 Appearance:
- It's a sphere-shaped like a pool 8 ball, with a cloudy liquid inside and a
visible window to display the answer.
 Answer types:
- The answers can be positive ("It is certain"), negative ("Don't count on it"),
or neutral ("Ask again later").
Randomness:

- The answers are generated randomly, usually by a 20-sided die floating in
the liquid.
 How to Implement Magic 8-ball Game in Python
We can implement the magic 8-ball game in Python using the randint() function
with if-else statements. Alternatively, we can also use the choice() function
defined in the random module in Python to implement the magic 8-ball game. Let
us discuss the choice() function with the list.
 Using The choice() Function
Instead of the randint() function, we can use the choice() function defined in the
random module to implement the magic 8-ball game. The choice() function takes
a list as its input argument and returns a random element from the list. We will
put all 20 answers in a list to implement the game. After this, whenever the user
asks a question, we will select a value from the list using the choice function and
print it as shown in the following example.

import random

answer_list=['It is certain.', 'It is decidedly so.', 'Without a


doubt.', 'Yes definitely.', 'You may rely on it.', 'As I see it,
yes.', 'Most likely.', 'Outlook good.', 'Yes.', 'Signs point to
yes.', 'Reply hazy, try again.', 'Ask again later.', 'Better not
tell you now.', 'Cannot predict now.', 'Concentrate and ask
again.', "Don't count on it.", 'My reply is no.', 'My sources say
no.', 'Outlook not so good.', 'Very doubtful.']

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 14


Introduction to Python Programming(BPLCK105B) - Module 2: Data Structures- Lists, Tuples and Dictionaries

while True:

question=input("Ask the magic 8 ball a question: (press enter


to quit) ")
if question=="":
print("Stopping the Game.")
break
answer_string=random.choice(answer_list)
print(answer_string)

Output:

Conclusion:
In above example, we have stored all the possible answers in a list. When the
user asks for an answer, we directly select a random answer from the list
using the choice() function and print it.

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 15


Introduction to Python Programming(BPLCK105B) - Module 2: Data Structures- Lists, Tuples and Dictionaries

 List-like Types: Strings and Tuples


o Lists aren’t the only data types that represent ordered sequences of values.
o Ex, we can also do these with strings: indexing; slicing; and using them with for
loops, with len(), and with the in and not in operators.
o To see this, enter the following into the interactive shell:

Output

 Mutable and Immutable Data Types ***(July 24-8M)

o Data types in Python are categorized into mutable and immutable data types.
o Mutable data types are those whose values can be changed once it is created.
Example: List, Dictionaries, and Set.
o Immutable data types are ones in which the values can’t be changed or altered
once they are created. Example: String and Tuples.
o Difference Between Mutable and Immutable Data Type: Mutable vs Immutable

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 16


Introduction to Python Programming(BPLCK105B) - Module 2: Data Structures- Lists, Tuples and Dictionaries

 String:
o String is immutable data type, whose elements cannot be changed once it is
created.
o Trying to reassign a single character in a string results in a TypeError error.

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

o We used [0:6] and [7:15] to refer to the characters we don’t wish to replace.
o Notice that the original 'Zophie a cat' string is not modified because strings are
immutable.
 List (June 2024-4M, July 24-8M)
o A list value is a mutable data type: It can have values added, removed, or
changed.

o 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]).

Figure: When eggs = [4, 5, 6] is executed, the contents of eggs are replaced
with a new list value.

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 17


Introduction to Python Programming(BPLCK105B) - Module 2: Data Structures- Lists, Tuples and Dictionaries

o If we want to modify the original list in eggs to contain [4, 5, 6], you would have
to delete the items in that and then add items to it.

Figure: The del statement and the append() method modify the same list value in place.

 The Tuple Data Type *** (July 24-6M)


o Tuples are immutable data types, whose values cannot be modified once they are
created.
o Tuples are used to store multiple items in a single variable.
o The tuple data type is identical to the list data type, except in two ways.
i. A tuple is a collection which is ordered and unchangeable.
ii. Tuples are written with round brackets ( ) rather than square brackets [ ].

o Example: Create a Tuple


Thistuple=("apple", "banana", "cherry")
print(thistuple)list

 Tuple Items:
o Tuple items are ordered, unchangeable, and allow duplicate values.
o Tuple items are indexed, the first item has index [0], the second item has
index [1] etc.
o The main way that tuples are different from lists is that tuples, like strings, are
immutable. Tuples cannot have their values modified, appended, or removed.

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 18


Introduction to Python Programming(BPLCK105B) - Module 2: Data Structures- Lists, Tuples and Dictionaries

o Example:

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


o The functions list() and tuple() will return the list and tuple versions of the
values passed to them. Example

 References:
o In Python, a reference is a name that points to the location of a value in
memory. References can be variables, attributes, or items.
o A variable is a name that refers to an object, and a reference is the connection
between the variable and the value. As variables store strings and integer values.

o In above example, we assign 42 to the spam variable, and then we copy the value
in spam and assign it to the variable cheese. When we later change the value in
spam to 100, this doesn’t affect the value in cheese. This is because spam and
cheese are different variables that store different values.
o But lists works differently. When we assign a list to a variable, we 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.

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 19


Introduction to Python Programming(BPLCK105B) - Module 2: Data Structures- Lists, Tuples and Dictionaries

o When we create the list ❶, we assign a reference to it in the spam variable. But
the next line copies only the list reference in spam to cheese, not the list value
itself. This means the values stored in spam and cheese now both refer to the
same list. There is only one underlying list because the list itself was never
actually copied.
o So when we modify the first element of cheese, we are modifying the same list
that spam refers to. List variables don’t contain lists—they contain references to
lists.

Figure: spam = [0, 1, 2, 3, 4, 5] stores a reference to a list, not the actual list.

o The reference in spam is copied to cheese. Only a new reference was created and
stored in cheese, not a new list.

Figure: spam = cheese copies the reference, not the list

o When we alter the list that cheese refers to, the list that spam refers to is also
changed, because both cheese and spam refer to the same list.
o Variables will contain references to list values rather than list values themselves.
o But for strings and integer values, variables will contain the string or integer
value.

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 20


Introduction to Python Programming(BPLCK105B) - Module 2: Data Structures- Lists, Tuples and Dictionaries

Figure: cheese[1] = 'Hello!' modifies the list that both variables refer to

o Python uses references whenever variables must store values of mutable data
types, such as lists or dictionaries. For values of immutable data types such as
strings, integers, or tuples, Python variables will store the value itself.

 Passing References

o References are particularly important for understanding how arguments get


passed to functions.
o When a function is called, the values of the arguments are copied to the
parameter variables. Example consider a program and its output

OUTPUT

o When eggs() is called, a return value is not used to assign a new value to spam.
Even though spam and someParameter contain separate references, they both
refer to the same list. This is why the append('Hello') method call inside the
function affects the list even after the function call has returned

 The copy Module’s copy() and deepcopy() Functions ***(July 24-6M)


o If the function modifies the list or dictionary that is passed, we may not want
these changes in the original list or dictionary value.
o For this, Python provides a module named copy that provides both the copy()
and deepcopy() functions.
o The copy module in Python has two functions that can be used to create copies of
objects: copy() and deepcopy():

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 21


Introduction to Python Programming(BPLCK105B) - Module 2: Data Structures- Lists, Tuples and Dictionaries

 copy()
o It can be used to make a duplicate copy of a mutable value like a list or
dictionary, not just a copy of a reference.
o Creates a shallow copy of an object. A shallow copy is a new compound object
that contains references to the original object's objects.

 deepcopy()
o Creates a deep copy of an object. A deep copy is a new compound object that
contains copies of the original object's objects.
 Consider the following example below the spam and cheese variables refer to
separate lists, which is why only the list in cheese is modified when you assign 42
at index 1. ➢ The reference ID numbers are no longer the same for both variables
because the variables refer to independent lists

Figure: cheese = copy.copy(spam) creates a second list that can be modified independently of the first.

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 22


Introduction to Python Programming(BPLCK105B) - Module 2: Data Structures- Lists, Tuples and Dictionaries

Chapter 5. Dictionaries and Structuring Data

5.1 The Dictionary Data Type (July 24-8M)


o Dictionaries are a fundamental data structure in Python.
o A dictionary is a collection that is ordered*, changeable and does not allow
duplicates.
o Dictionaries are used to store data values in key: value pairs.
o Dictionaries can use many different data types, not just integers.
o Dictionaries are written with curly brackets, and have keys and values:
o Indexes for dictionaries are called keys.
o The dictionary data type provides a flexible way to access and organise data.

o Example:

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

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 23


Introduction to Python Programming(BPLCK105B) - Module 2: Data Structures- Lists, Tuples and Dictionaries

5.2.1 Dictionaries vs. Lists *** (July 2024-4M)

Lists Dictionaries
Dictionaries are an unordered collection of
List is an ordered collection of items.
data in a key: value pair form.
Uses square brackets [ ]. Uses curly braces { }.

Ex: fruits = [“apple”, “banana”, “cherry”] Ex: person = {“name”: “John”, “age”: 30}
Ordered: Items have a defined order,
Unordered: Items do not have a defined order.
which will not change.
Accessed by index, starting from 0. Values are accessed using keys.
Does not allow duplicate keys. However,
Allows duplicate items.
values can be duplicated.
Keys can be of any immutable data type (e.g.,
It can store any data type. strings, numbers, tuples). Values can be of any
type.
Built in functions: append(), remove(), Built in functions: keys(), values(), items(),
pop(), sort(), etc. get(), pop(), etc.
Dictionaries can not be sliced.
Slicing can be done

5.2.2 The keys(), values(), and items() Methods: (July 2024-8M, Jan2024-8M)
o Three dictionary methods will return list-like values of the dictionary’s keys,
values, or both keys and values: keys( ), values( ), and items( ).
o The values returned by these methods are not true lists: They cannot be
modified and do not have an append( ) method.
o for loop iterates over each of the values in the spam dictionary.

o for loop can also iterate over the keys or both keys and values: Example

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 24


Introduction to Python Programming(BPLCK105B) - Module 2: Data Structures- Lists, Tuples and Dictionaries

o Obtain the True list from the dictionary: Example

o The list(spam. keys()) line takes the dict_keys value returned from keys() and
passes it to list(), which then returns a list value of ['color', 'age'].
o Multiple assignment trick in a for loop to assign the key and value to separate
variable: Example below

5.2.3 Checking whether a key or value exists in a dictionary


o Use in and not in operators can check whether a value exists in a list.
o For example:

5.2.4 The get( ) Method (Jan-2024-6M)


o The get() method returns the item's value with a specified key.
o Dictionaries have a get() method that takes two arguments:
o The key of the value to retrieve and a fallback value to return if that key does
not exist. For example

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 25


Introduction to Python Programming(BPLCK105B) - Module 2: Data Structures- Lists, Tuples and Dictionaries

o Because there is no 'eggs' key in the picnicItems dictionary, the default value 0 is
returned by the get() method.
o Without using get(), the code would have caused an error message, such as in the
following example:

5.2.5 The setdefault() Method


o The setdefault() method offers a way to do this in one line of code.
o The first argument passed to the method is the key to check for, and the second
argument is the value to set at that key if the key does not exist.
o If the key does exist, the setdefault() method returns the key’s value.

o The first time setdefault() is called, the dictionary in spam changes to {'color':
'black', 'age': 5, 'name': 'Pooka'}.
o The method returns the value 'black' because this is now the value set for the key
'color'.
o When spam. setdefault('color', 'white') is called next, the value for that key is not
changed to 'white' because spam already has a key named 'color'.

5.2.6 Pretty Printing


o Pretty print (pprint) is a useful built-in module in Python.
o PPrint stands for "Pretty Print", and is one of the native Python libraries allowing
to customise outputs with numerous parameters.
o The Python module pprint is used for giving proper printing formats to various
data objects in Python.

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 26


Introduction to Python Programming(BPLCK105B) - Module 2: Data Structures- Lists, Tuples and Dictionaries

o Importing the pprint module gives you access to the pprint() and pformat()
functions, which can “pretty print” a dictionary’s values.
o In the below example we see how that data looks before applying the pprint
module and after applying it.

5.2.7 Using Data Structures to Model Real-World Things

 A Tic-Tac-Toe Board
o Tic Tac Toe is a puzzle game for two players, called "X" and "O", who take turns
marking the spaces in a 3×3 grid. The player who succeeded in placing three
respective marks in a horizontal, vertical, or diagonal row wins the game.
o 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,
we can assign each slot a string-value key as shown in below figure.

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 27


Introduction to Python Programming(BPLCK105B) - Module 2: Data Structures- Lists, Tuples and Dictionaries

Figure: The slots of a tic-tac-toe board with their corresponding keys


o We can use string values to represent what’s in each slot on the board: 'X', 'O', or
' ' (a space character).
o To store nine strings. We can use a dictionary of values for this.
- 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.

o Store this board-as-a-dictionary in a variable named theBoard.

o The data structure stored in the theBoard variable represents the tic-tactoe
board in the below Figure 5.3

Figure 5-3: An empty tic-tac-toe board


o Since the value for every key in theBoard is a single-space string, this dictionary
represents a completely clear board. If player X went first and chose the middle
space, you could represent that board with this dictionary as shown below:

Figure: A first move

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 28


Introduction to Python Programming(BPLCK105B) - Module 2: Data Structures- Lists, Tuples and Dictionaries

o A board where player O has won by placing Os across the top might look like
this:

o The data structure in theBoard now represents the tic-tac-toe board in Fig 5-5.

o The player sees only what is printed to the screen, not the contents of variables.
o The tic-tac-toe program is updated as below.

o When you run this program, printBoard() will print out a blank tic-tac toe board.

o The printBoard() function can handle any tic-tac-toe data structure you pass it.

o Now when you run this program, the new board will be printed to the screen.

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 29


Introduction to Python Programming(BPLCK105B) - Module 2: Data Structures- Lists, Tuples and Dictionaries

o Now we created a data structure to represent a tic-tac-toe board and wrote code
in printBoard() to interpret that data structure, we now have a program that
“models” the tic-tac-toe board.
o Program: allows the players to enter their moves.

o When you run this program, it will look something like this:

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 30


Introduction to Python Programming(BPLCK105B) - Module 2: Data Structures- Lists, Tuples and Dictionaries

 Nested Dictionaries and Lists: (July 24-6M)


o We can have program that contains dictionaries and lists which in turn contain
other dictionaries and lists.
o Lists are useful to contain an ordered series of values, and dictionaries are useful
for associating keys with values.
o Program: which contains nested dictionaries in order to see who is bringing
what to a picnic

o Inside the totalBrought() function, the for loop iterates over the keyvalue pairs in
guests 1.
o Inside the loop, the string of the guest’s name is assigned to k, and the dictionary
of picnic items they’re bringing is assigned to v.
o If the item parameter exists as a key in this dictionary, it’s value (the quantity) is
added to numBrought 2.
o If it does not exist as a key, the get() method returns 0 to be added to
numBrought.
o The output of this program looks like this:

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 31


Introduction to Python Programming(BPLCK105B) - Module 2: Data Structures- Lists, Tuples and Dictionaries

VTU MODULE- 2 QUESTIONS

 JUNE- 2024

 JULY - 2024

 JULY - 2024

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 32


Introduction to Python Programming(BPLCK105B) - Module 2: Data Structures- Lists, Tuples and Dictionaries

 Dec-2023/Jan 2024

 Dec-2023/Jan 2024

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 33


Introduction to Python Programming(BPLCK105B) - Module 2: Data Structures- Lists, Tuples and Dictionaries

 NOV/DEC -2023

 JUNE/JULY -2023

Acknowledgement:
My sincere thanks to the author Al Sweigart, because the above contents are
prepared from his textbook “Automate the Boring Stuff with Python:
Practical Programming for Total Beginners”
Prepared by:
Dr. Suresha V
Professor & Principal
Dept. of Electronics and Communication Engineering.
Reach me at: [email protected]
WhatsApp: +91 8310992434

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 34

You might also like