0% found this document useful (0 votes)
6 views24 pages

M 2

This document provides an introduction to the List data type in Python, covering its structure, indexing, slicing, and methods for manipulating lists. It explains how to create lists, access their elements, modify values, and utilize various list operations such as concatenation and deletion. Additionally, it discusses the use of loops and conditional statements to work with lists effectively.

Uploaded by

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

M 2

This document provides an introduction to the List data type in Python, covering its structure, indexing, slicing, and methods for manipulating lists. It explains how to create lists, access their elements, modify values, and utilize various list operations such as concatenation and deletion. Additionally, it discusses the use of loops and conditional statements to work with lists effectively.

Uploaded by

Keerthana Balaji
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 24
Introduction to Python Programming (BPLCK105B/205B) Module 2 CHAPTER 1: LISTS 1. 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 1.1 The List Data Type A list is a value that contains multiple value: ‘an ordered sequence. A ist value looks like this: [cat "bat, rat, ’elephant]. A list begins with an opening square bracket and ends with a closing square bracket, [] vvvyv ‘Values inside the list are also called items and are separated with commas So i a a ene) bp) (eat'y ‘bat! ‘rat! ‘elephant") (eats Sobers Yade's elephant’) pep ffane' 9-25, oss Aone © 353 span’ feat 333 Spam eater nats > The spam variable @ is still assigned only one value: the list value(contains multiple values). > The value [] is an empty list that contains no values, similar to ", the empty string. jetting Individual Values in a List ith Indexes > Say you have the list [‘cat’, "bat, ‘rat, 'elephant'] stored in a variable named spam, > The Python code spam{0] would evaluate to 'cat’, and spam[1] would evaluate to ‘bat’, and so on. spam = ["cat", "bat", "rat", “elephant"] spanio] spam[a]span{2]_ span{3] > The first value in the list is at index 0, the second value is at index 1, and the third value is at index2, and so on. > For example, type the following expressions into the interactive shell. SEEERERE, sae, rae, ‘etephont aEaT Bolle «+ spantor {he bet ate Theeat.? > _.wJ|,— Introduction to Python Programming (BPLCK10SB/20SB) Module 2 > ‘The expression ‘Hello ' + spam[0] evaluates to 'Hello' + ‘cat! because spam{0] evaluates to thestring ‘cat. This expression in turn evaluates to the string value 'Hello cat’ > If we use an index that exceeds the number of values in the list value then, python gives IndexError. >>> span = [‘eat', ‘bat’, ‘zat’, ‘elephant'] >> span{20000] Traceback (wst recent all last): File "apyshellis>", Line 1, in enodules san{ 10000) Tndedérror: List index out of range > Indexes can be only integer values, not floats. The following example will cause a TypeEtror error: >> spans [‘eat', ‘bat', ‘rat, ‘elephant'] >>> span[t] "bat" >>> span[t0] Traceback (vost recent call last) File “cpyshell#i>*, line 1, in emdsley span1.0] Typetrror: List indices must be integers, not float >>> spanfint(2.0)], "bat > Lists can also contain other list values. The values in these lists of lists can be accessed using multiple indexes. >o> span{o] [at’, “hat'] >>> span[o]E3] "hat! >> spai]E4] 50 > The first index dictates which list value to use, and the second indicates the value within the listvalue. Ex, spam[0][1] prints ‘bat’, the second value in the first list. Negative Indexes > We ean also use negative integers for the index. The integer value -I refers tothe last index in a list,the value -2 refers to the second-to-last index in a list, and so on. >» span = ["cat', ‘bat’, ‘zat’, ‘elephant’] >> span[-1] “elephant! > sa-3] "bat o> "The ' + spanf-1] + ' is afraid of the ' + spanl-3] +‘ "The elephant is afraid of the bat." caw Introduction to Python Programming (BPLCK105B/20SB) Module 2 tting Sublists with Slices > An index will get a single value from a list, a slice can get several values from a list, in the form of anew list. > A slice is typed between square brackets, like an index, but it has two integers separated by a colon. > Difference between indexes and slices. ‘© spam(2] is alist with an index (one integer). (© spam{ 1:4] isa list with a slice (two integers) > Ina slice, the first integer is the index where the slice starts. The second integer is the index wherethe slice ends (but will not include the value at the second index). 29> span = [‘eat!, ‘bat’, ‘vat’, ‘elephant'] >> span[o:4) (‘cat', ‘bat’, ‘rat’, ‘elephant ] >>> span(t:3] ['bat', "rat"] >> span[o:-1] ['cat', ‘bat’, ‘rat'] > Asa shortcut, 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, or the beginning of the list. © Leaving out the second index is the same as using the length of the list, which will slice tothe end of the list. >> spams [‘eat', ‘bat’, ‘rat, ‘elephant'] >>> spanl 2] Coat’, ‘bat'] >>> spanft:] ['bat', ‘rat! ‘elephant"] vy span] ('cat’, ‘bat’, ‘rat', ‘eleptant'] Gotti ists ‘i > The len() function will return the number of values that are in list value. >> span = [leat >v> len(span) 3 hanging Values in a List with In > We can also use an index of a list to change the value at that index. Ex: spam[1] = ‘aardvark’ means"“Assign the value at index 1 in the list spam to the string ‘aardvark',” => Introduction to Python Programming (BPLCK10SB/20SB) Module 2 D> span = [eat’, “bat, rat’, “elephant ] o> apan[S] » "aatdvank 3 pam (eat, “aardvasky rat", “elephant"] >> spina] = sana] >> span Creat, taardvank’, ‘aardvare’, ‘eleptont*] >>> santa] = 22345 >>> span (eat, aardvark’, ‘aardvar’, 85 ist Concatenation and List Replication > The + operator can combine two lists to create a new list value in the same way it combines ‘twostrings into a new string value, > The * operator can also be used with a list and an integer value to replicate the list. do [2 a] + Pa, 8, IC] (23,18), (BY fc’) oa (hey wy iz] ea DY a hs ES RET de> span © [3,"2, 3] >>> span = span ¢ [A 1 >e> span [a a Removing Values from Lists with del Statements ee > The del statement will delete values at an index ina list. >> span = Cat’, “bat', “at's “elepha >>> del spaal2] >> span ['eat', “bat! ‘elephant*] >>> del. spam(2] >> span (oath, that") > The del statement can also be used to delete a variable After deleting if we try to use the variable, we will get a NameEtror error because the variable no longer exists. > Inpractice, you almost never need to delete simple variables. > The del statement is mostly used to delete values from lists. 1.2 Working with Lists > When we first begin writing programs, it’s tempting to create many individual variables to store a groupof similar values. catNamea = 'Zophie' catName2 = 'Pooka" catName3 = 'Simon* catNameg = ‘Lady Macbeth’ catName5 = 'Fat-tail’ catNames => "Miss Cleo" Introduction to Python Programming (BPLCK10SB/20SB) Module 2 > Which is bad way to write code because it leads to have a duplicate code in the program, print (‘Enter the none of ext 42 catered = input() print (‘Enter the are of eat 2:') Catone = input) Print Pater the nase of eat 3:') Cstlane) » input) print(‘Enter the none oF eat 4: ates = input) print(‘Enter the ane of cat 5:') ‘atNane5 = int) print(‘Enter the rane of cat 6:") Cathanes = Inut() print ("the cat nave aze:") print(cathanes +" + canes + ' ' + cotNanes +" + catlones 4 44 cathanes +‘ + cattonet) > Instead of using multiple, repetitive variables, we can use a single variable that contains a list value. > For Ex: The following program uses a single list and it can store any number of cats that the user typesin, > Program: ccatNiones - [1 nse True: print(‘Enter the nane of cat "(Gr enter nothing to stop. input) _str(Len(catNanes) +3) + Sf nape break catNanes = catNanes + [name] List concatenation print(“The eat names are:") ffor nane in catNanes print(* * + name) > Output Enter the name of cat 2 (Or enter nothing to stop Zophie Enter the nane of cat 2 (Or enter nothing to stop.) Pooks, Enter the nane of cat 3 (Or enter nothing to stop.) Sinon Enter the none of cat 4 (Or enter nothing to stop. Lady Macbeth Enter the nane of cat 5 (Or enter nothing to stop.): Fat-tail Enter the nane of cat 6 (Or enter nothing to stop.): Miss Cleo Enter the name of cat 7 (Or enter nothing to stop. The cat names are: Zophie Pooka Sinon Lady Macbeth Fat-tail Miss Cleo }> The benefit of using a list is that our data is now in a structure, so our program is much more flexible inprocessing the data than it would be with several repetitive variables. => Introduction to Python Programming (BPLCK10SB/20SB) Module 2 Using for Loops with Lists > A for loop repeats the code block once for each value in a lst of list-like value. Program for 1 in rarge(a) peint(i) ‘Output: ° 1 2 3 > A common Python technique is to use range (Ien(someList)) with a for loop to iterate over theindexes of a list. o> supplies = [‘pons', ‘staplers', “flane-throvers", ‘binders >»> for i in range(Jen(supplies)): print("Index ' + stz(i) + ' in supplies is: + supplies(3]) Index 0 in supplies is: pens Index 1 in supplies is: staplers Index 2 in supplies is: Flane-throwers Index 3 in supplies is: binders > The code in the loop will access the index (as the variable i), the value at that index (as supplies{i)Jand range(len(supplies)) will iterate through all the indexes of supplies, no matter how many items it contains. The in and not in Operators > We can determine whether a value is or isn’t in a list with the in and not in operators, > im and not in are used in expressions and connect two values: a value to look for in a list and the listwhere it may be found and these expressions will evaluate to a Boolean value. SS3 “howdy” dn [onedle", “he's “hondy", “heyas"T SS spam a Cihettots ms “hows “heyan] SEP cats not Sn spam > The following program lets the user type in a pet name and then checks fo see whether the name isin a list of pets. Program ytets = [Zophicr, “Pooks, Fat tail'] int (Enter pet name") Bee tome Prine( 1 donot have a pet named awe) Print (name + * 63 ay pet. => Introduction to Python Programming (BPLCK10SB/20SB) ‘Output Module 2 Enter a pet nane Footfoot T do not have a pet naned Foot foot The Multiple Assignment Trick > ‘The multiple assignment trick is a shorteut that lets you assign multiple variables with the values ina list in one line of code. ooo cat = ['fat", ‘black’, "loud'] ooo eat = ['fat!, ‘black’, ‘Loud! ] >>> size = catfo} >>> size, color, disposition = cat 333 color = eat[3] —e“—eowsvvwwnr_e<=, >>> disposition = cat[2] } Instead of left-side program we could type the right-side program to assignment multiple variables but the number of variables and the length of the list must be exactly equal, or Python will give youa ValueError: >>> cat = ['fat', ‘black’, "Toud"} >») size, color, disposition, nane = cat Traceback (nost recent call Lact File “cpyshell#84>", line 1, in size, color, disposition, ane = cot Valuetrror: need more than 3 valves to unpack 1.3 Augmented Assignment Operators > When assigning a value to a variable, we will frequently use the variable itself, >>> pam = 4 o> spa >>> spam = sam +1 >>> span So spam >>> spam a a } Instead of left-side program we could use right-side program ic., with the augmented assignmentoperator += to do the same thing as a shortcut. jisted in the below table: v ‘The Augmented Assignment Operators are ‘Augmented assignment statement Equivalent avsignment statement span = spam + 1 Spam ved span = pom — 4 spam =a span = spam #1 spate a span 1 ‘pam fo 3 spa 1 spam te 3 > The + operator can also do string and list concatenation, and the *= operator can do string and listreplication, 33 spam 4= ‘world! 33) spam ‘Helo world!" boos bacon = [*2ophie"] >> bacon t= 3 3>> bacon [iophie", "Zophie* 39> spam = "HeTIo! ‘ophie"| —=T Ss. M082 Introduction to Python Programming (BPLCK105B/20SB) Module 2 1.4 Methods > A method is same as a function, except it is “called on” a value, The method part comes after the value, separated by a period, > Each data type has its own set of methods. The list data type has several useful methods for finding, adding, removing, and manipulating valuesin a list. inding a Value in a ith the index() Method > List values have an index() method that can be passed a value, and if that value exists in the list, theindex of the value is returned, If the value isn’t in the list, then Python produces >>> span. index( hello’) ° >>> span.index( "heyas' 3 >>> span-index( ‘howdy houdy howy") Trscaback (most recent call last): File "cpyshel#31>", Line 1, in caoduley span. index( ‘howdy’ howdy howdy") Valuetxcor: “howdy howdy howiy' is not Jn list ValueError error. > When there are duplicates of the value in the list, the index of its first appearance is returned. >>) spam = ["Zophie", “Pooka’, ‘Fat-tail’, ‘Pooka*] >>> spam. index( ‘Pooka’ ) 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. >>> spam = [‘cat', “dog’, "bat ] >>) span.append( ‘noose") >>> spam [‘cat!, "dog", bat", ‘noose'] > The insert() method can insert a value at any index in the list. The first argument to insert() is theindex for the new value, and the second argument is the new value to be inserted. ooo spam = [‘eat", ‘dog’, ‘bat"] >>> span.insert(a, “chicken’) >>> span Liat, ‘chicken’, ‘dog’, *hat") v Methods belong to a single data type. => Introduction to Python Programming (BPLCK105B/205B) Module 2 > The append() and insert() methods are list methods and can be called only on list values, not onother values such as strings or integers. >>) agge = ‘hello! >>> eggs.append( world") ‘Traceback (nost recent call Last): File “cpyshell#i92", Line 1, in >> bacon = 42 >>> bacon.insert(a, ‘world") Traceback (nost recent call lest): Fale " ‘The remove() method is passed the value to be removed from the list it is called on. ooo gpam = [ea >>> spam.xenove( bat") >>> spam Cat’, ‘rat elephant’) > Attempting to delete a value that does not exist in the list will result in a ValueError error. de> spam = [‘eat', ‘bat', “zat! >>> span.renove( chicken’) Traceback (ost recent call Last): File "epyshell#at>", Line 1, in ‘spon. renove( ‘chicken') Valuetrror: List.renove(x): x not in 1ast elephant") > Ifthe value appears multiple times in the list, only the first instance of the value will be removed. >>> span = [‘eat!, ‘hat', ‘rat', ‘eat, ‘hat, ‘eat'] >>) span.renove( Cat") >>> spam Uibat', ‘rat's ‘cat! that's ‘cat > 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. Sorti ¥; ina List wi (Method > Lists of number values of lists of strings can be sorted with the sort() method. >>> spam = [2, 5, 3.44, 4, -7] >>> spam.sart() >>> spam [-1, 1,2, 324, 5] >>> spam = [‘ants*, “cats, “dogs”, "badgers", ‘elephants’] >>> spam.sort() Soo spam [lants’, ‘badgers’, ‘cats’, ‘dogs’, ‘elephants'] => _Casw>ww4>s>swt Introduction to Python Programming (BPLCK105B/205B) Module 2 > You can also pass True for the reverse keyword argument to have sort() sort the values in reverseorder. >>> spam.sort(reverse=True) >>> span ['elephants', "dogs", ‘cats’, "badgers", ‘ants’ | > ‘There are three things you should note about the sort() method. (©. First, the sort() method sorts the list in place; don’t ry to return value by writing code likespam = spam.sort() © Second, we cannot sort lists that have both number values and string values in them, >>> spam = (1, 3, 2 & >>> spansort() Traceback (wost recent call Last): File “cpysteLl#70)", line 1, in spam, sort() ‘TypeError: unorderable types: str() < int() © Third, sor() uses “ASCIIbetical order(upper case)” rather than actual alphabeticalorder(lower case) for sorting strings. >>> spam = ["Alice', ‘ants', ‘Bob’, ‘badgers', ‘Carol’, ‘cats'] >>> span-cort() >>> spam ['Alice’, "Sob", ‘Carol', ‘ants’, ‘badgers’, ‘cats*] > If we need to sort the values in regular alphabetical order, pass str-lower for the key keyword argument in the sort() method call ooo spam = ['2", (25, 1A, 2) >>> spam.sort(keysstz Lower) >>> span 1.5 Example Program: Magic 8 Ball with a List > We can write a much more elegant version of the Magic 8 Ball program. Instead of several lines ofinearly identical elif statements, we can create a single list. Sinport randon meccages = ['Tt is corts “Tt is decidedly so’, “Yes definitely’, “Reply hazy try agai ‘ask again late: “concentrate and ask again’, “ny zeply is n'y “outleok nat so goad’, “Very doubt ful’ | print (nessages[randk fandint (0, len(nessages) 2) > 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 piece Introduction to Python Programming (BPLCK105B/20SB) Module 2 is, you’llget a random number between 0 and the value of len(messages xceptions to Indentation Rules in Python > The amount of indentation for a line of code tells Python what block it is in. > lists can actually span several lines in the source code file. The indentation of these lines, do notmatter; Python knows that until it sees the ending square bracket, the list is not spam ~ [‘apples', ‘oranges’, ‘bananas’, “eats print (span) finished. > We can also split up a single instruction across multiple lines using the \ line continuation, characterat the end, print("Four score ard coven ' 4 \ “years ago...") 1.6 List-like Types: Strings and Tuples > Lists aren’t the only data types that represent ordered sequent sof values, > Ex, we can also do these with strings: indexing; slicing; and using them with for loops, with Jen(),and with the in and not in operators. Mutable and Immutable Data Types String > However, a string is immutable: It cannot be changed. Trying to reassign a single character in astring results in a TypeEttor error. >>> nane = 'Zophie 3 cat* >>> nane{7] = ‘the Traceback (nost recent call Last): File "cpyshel1#50>", Line 4, in naa} = ‘the! Typetrror: ‘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 bycopying from parts of the old string, ————Ea—=eeaO Introduction to Python Prog mming (BPLCK105B/205B) Module 2 >>> name = ‘Tophie a cat” >>> newtlane = name[0:7] + ‘the’ + nane[8: 22] “Zophie a cat” >>> neidlane “Zophie the cat’ > We used [0:7] and [8:12] to refer to the characters that we don’t wish to replace. Notice that theoriginal 'Zophic a cat’ string is not modified because strings are immutable. List > A list value is a mutable data type: It can have values added, removed, or changed, >> eggs = (2, 2, 3] >>> ens = [4, 5, 6] >>> eggs Uh 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]). = >." | Figure: When eggs = [4, 5, 6] is executed, the contents of eggs are replaced with a new list value. > If we want to modify the original list in eggs to contain [4, 5, 6}, you would have to delete the itemsin that and then add items to it. spy bs Figure: The del statement and the append() method modify the same Tist value in place. The Tuple Data Type > The tuple data type is almost identical to the list data type, except in two ways. a Introduction to Python Programming (BPLCK105B/205B) Module 2 o> eage >>> eggs [o] “helle™ >>> epgs{4:3] (42,045) >>> len(egge) 3 *helle', 42, 0.5) v Second, benefit of using tuples instead of lists is that, because they are immutable and their contentsdon’t change. Tuples cannot have their values modified, appended, or removed, >>) eggs = (‘hello’, 42, 0.8) >>> eggs(a] = 99 Traceback (nost xecent call last): File "qystellA)", Line 2, in exgs[] - 99 ‘TypeError: ‘tuple’ object does not support item assignnent > Ifyou have only one value in your tuple, you can indicate this by placing a trailing comma after thevalue inside the parentheses. >>> type( ("hello >>> type((*helle")) ) ver s with tI a > ‘The functions list() and tuple() will return list and tuple versions of the values passed to them. >>> tuple({'cat', ‘deg", 51) Coat’, “dog, 5) pep List((‘cat', ‘dog's 5)) Uicat’, "dog’, 5] d>> List( ‘hello') Paty setts ay tot > Converting a tuple to a list is handy if you need a mutable version of a tuple value. 1.7 References > As we've seen, variables store strings and integer values. So> span = 42 >>> cheese = spam >>> span = 200 >> span 1100 >>> cheese 2 > We assign 42 to the spam variable, and then we copy the value in spam and assign it to the variablecheese, When we later change the value i spam to 100, this doesn’t affect the value in cheese, Thisis because spam and cheese are different variables that store different values. v But lists work 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 alist reference isa value that points to a lst. SU IESE Introduction to Python Programming (BPLCK105B/205B) Module 2 > 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. © >>> span = [0, 4, 2, 3, 4, 5] © >>> cheese = Span © 53> cheese[] = ‘Hello! >> spam [0, ‘Hellol', 2 3, 4 5] >>> cheese [0, ‘Hellol', 2, 3 4 51 > There is only one underlying list because the list itself was never actually copied. So when ‘we modify the first element of cheese, we are modifying the same list that spam refers to. > List variables don’t actually contain lists—they contain references to lists. + 10,1. 2, 3.4, 5] Figure: spam = [0, 1, 2,3, 4,5] stores a reference toa list, not the actual list. } The reference in spam is copied to cheese. Only a new reference was created and stored in cheese,not a new list Figure: spam. ‘heese copies the reference, not the list v When we alter the list that cheese refers to, the list that spam refers to is also changed, because bothcheese and spam refer to the same list. cheese[! "Hello!’ modifies the list that both variables refer to v Variables will contain references to list values rather than list values themselves. v But for strings and integer values, variables will contain the string or integer value, v 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 variableswill store the value itself. =>. Introduction to Python Programming (BPLCK105B/205B) Module 2 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. et epas (soneParameter): ‘SoneParanter.apperd( Helo") spam = [15 2, 3] ezgs(span} print (spam) [4, 2, 3, ‘Hello") Program Output > 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() Function: > Ifthe function modifies the list or dictionary that is passed, we may not want these changes in theoriginal list or dictionary value. > For this, Python provides 2 module named copy that provides both the copy() and deepcopy()funetions, > copy(), can be used to make a duplicate copy ofa mutable value like a list or dictionary, not just acopy of'a reference. v Now the spam and cheese variables refer to separate lists, which is why only the list in cheese ismodified when you assign 42 at index 1 > The reference ID numbers are no longer the same for both variables because the variables refer toindependent lists, hermes 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. Introduction to Python Programming (BPLCK105B/20SB) Module 2 CHAPTER2: DICTIONARIES AND STRUCTURING DATA 1. The Dictionary Data Type 2. Pretty Printing 3. Using Data Structures to Model Real-World Things. 2. The Dicti Ty > A dictionary is a collection of many values. Indexes for dictionaries can use many different data types, not just integers. Indexes for dictionaries are called keys, and a key with its associated valueis called a key-value pair. > A dictionary is typed with braces, {}. >>> 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. You can access these values through their keys: de> ayCat [ize] “at” >>> ‘My cat has * + myCat[ color) + * furs! “wy cat has gray fur. > Dictionaries can still use integer values as keys, but they do not have to start at 0 and can be any number. >>> span = (12345: ‘Luggage Combination’, 42: ‘The Answer’ } Dictionaries vs. Lists > Unlike lists, items in dictionaries are unordered, v ‘The first item in a list named spam would be spam[0]. But there is no “first” item in a dictionary. While the order of items matters for determining whether two lists are the same, it does not rmatterin what order the key-value pairs are typed in a dictionary. >>> spam = [leats', ‘dogs’, ‘noose'] >>> bacon = ["dogs', ‘moose, ‘cats"] bacon rane’: ‘Zophie', ‘species’: ‘cat’, ‘age’: '8'} {Cspecies': ‘eat', *age': ‘8, ‘name’: "Zophic") >>> eggs == ham True > ‘Trying to access a key that does not exist in a dictionary will result in a KeyEtror error message, much like a list’s “out-of-range” IndexError error message. =>. Introduction to Python Programming (BPLCK105B/205B) Module 2 >>> Spam = {'nane*: ‘Zophie’ >>) span 'coler"] Teaceback (east recent call last): Fale “cpysheliti>", Line 4, 31 sponl‘eolor'] Keyrror: ‘color’ > Weecan have arbitrary values for the keys that allows us to organize our data in powerful ways. > Ex: we want to store data about our friends’ birthdays. We can use a dictionary with the names as keys and the birthdays as values. (birthdays = {Alice's “ipra!, o's "Dee 12", “Cara's ar vile Tae pelst(Enter a nate: (Bank to ait)") Eee s er Glew ee © eae fy itis: Eiker a'ranes (lane 20 ak pent(hplome] + ise bith of ve) ae owe hve Birthiay ffornton for ve Prn(1 dat hve birth fot a ng) Meh hee Bat pnt(Mhat is thei bith?) Bizehday datasese updated. lays tt) Enter a rane (anc 0 58) © itiasfranel = bey BEE 5 As the birthday of eve pint Bithay tase pate") Enver avrane: (olan 20 9102) Program Output > We ereate an initial dictionary and store it in birthdays 1. > We can see if the entered name exists as a key in the dictionary with the in keyword 2. > Ifthe name is in the dictionary, we access the associated value using square brackets 3; if not, we can add it using the same square bracket syntax combined with the assignment operator 4. The keys(), values(), and items Methods > There are three dictionary methods that will return list. values,or both keys and values: keys(), values(), and items(). > Data types (dict_keys, dict_values, and dict_items, respectively) can be used in for loops. >>) for v in span.valves(): print(v) ed a > A for loop can iterate over the keys, values, or key-value pairs in a dictionary by using keys(),values(), and items() methods. > The values in the dict_items value returned by the items() method are tuples of the key and value. => Introduction to Python Programming (BPLCK105B/205B) Module 2 Sos for K dn apembeys(): priate) SES eer < an epam-stone() print) Cooter", *zed") Cage's day v Ifwe want a true list from one of these methods, pass its list-like return value to the list() function. D> spam = (Veolor': "red", ‘age': 42} >>> span. keys() dict keys({'eolor',,‘age']) >>> List(span.keys()) Ucolor', ‘age'] > 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’]. > We-can also use the multiple assignment trick in a for loop to assign the key and value to separatevariables, “+ ste) Keay: age Value: 42 ey: color Value: red Checking Whether a Key or Value Exists in a nary We can use the in and not in operators to see whether a certain key or value exists in a dictionary. 333 Mhame™ in" Spam-keys@) 23>" "Zophie’ in spam-values() 353" ‘color’ in spam-keys() False Soy Scotert nat in spam-keys() 333" *color* in spam The get) Metho Dictionaries have a get() method that takes two arguments: © The key of the value to retrieve and (© A fallback value to return ifthat key does not exist So) plenicTtens = (‘apples': 5, ‘cups’: 2) >>> "Lan bringing * + str(picnicttens.get("cups’, 0)) + ° cups." "Lam bringing 2 cups." o> 'T an bringing ' + str(picnicttenc.get("eggs', 0) + ' egge." “Lam bringing 0 eggs." The setdefault() Method } To seta value ina dictionary for a certain key only if that key does not already have a value. =>. Introduction to Python Programming (BPLCK105B/205B) Module 2 spam Gf ‘color’ not in span: span|‘coler’] - ‘black > The setdefault() method offers a way to do this in one line of code, > Setdeafault() takes 2 arguments: © The first argument is the key to check for, and. © The second argument is the value to set at that key if the key does not exist. Ifthe key does cxist,the setdefault() method returns the key’s value. de> spam = (Unane': "Pocka', ‘age': 5} >> span.setdefault(*color', “black’ ) "black" >>> spam (color': ‘black’, ‘age': §, ‘rane’: “Pocka’) >>> span.setéefault( color’, ‘white’ ) “black! >>> spam Ccoler': “black", ‘age rane’: “Pocka"} > The first time setdefault( is called, the dictionary in spam changes to {'color’:"black’, ‘age’: 5, ‘name: "Pooka'}. The method retums the value ‘black’ because this is now the value set for the key ‘color’. Whenspam.setdefault(color, white’) is called next, the value for that key is not changed to 'white’ because spam already has a key named ‘color. > Ex: program that counts the number of occurrences of each letter in a string, message : count. Tt was a bright cold day in April, and the clocks were striking thirteen ) for character in message: count. setdefeult (character, 0) count |chazacter] = count[character] + 4 print(count) > ‘The program loops over each character in the message variable’s string, counting how often, eachcharacter appears. > The setdefault() method call ensures that the key is in the count dictionary (with a default value of 0), sothe program doesn’t throw a KeyError error when count{character] = count{character] + 1 is executed > Output: 2.2 Pretty Printing > Importing pprint module will provide access to the pprint() and pformat() functions that will “prettyprint” a dictionary’s values. > This is helpful when we want a cleaner display of the items in a dictionary than what print() providesand also itis helpful when the dictionary itself contains nested lists or dictionaries pa ep er een ee, Introduction to Python Programming (BPLCK105B/205B) Module 2 Brogeam:; counts the number of occurrences of each letter in a string. import pprint message = ‘It was a bright cold day in April, and the clocks were striking ‘thirteen. count = () for character in message: count setdefaul (character, 0) count(character] ~ count{ character] + 1 print pprint (count) CEAORUOSR REIN G EN TUH Ds | > Ifwe want to obtain the prettified text as a string value instead of displaying it on the screen, call pprint.pformat(), porint.pprint(soneDicticnaryWalue) Print (pprint pfoxmat(soneDict ienary/a]ue)) > 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 shownin below figure. Introduction to Python Programming (BPLCK105B/20SB) Module 2 Figure: The slots ofa tic-tactoe board with their corresponding keys v ‘We can use string values to represent what's in each slot on the board: X’,'0', or" (a space character) v 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, tring value with the key low-L’ can represent the bottom-left corner, ¢ string value with the key 'mid-M can represent the middle, and so on > Store this board-as-a-dictionary in a variable named theBoard, theBoard = ("top-Le |", ry. iald-L': * i nacue y > The data structure stored in the theBoard variable represents the tic-tactoe board in the below Figure. Figure: An empty tic-tae-toe board > 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 v ‘A board where player O has won by placing Os across the top might look like this: =>. Introduction to Python Programming (BPLCK105B/20SB) Module 2 ‘thetioard > The player sees only what is printed to the screen, not the contents of variables. > The tic-tac-toe program is updated as below. theboand = (Vtop-U's | 4, Mapas |S Nope med-L' ty idem: mide: Tel 8) “lowent 8) “lowe: def printBoard( board print board["top-L'] + *|' + board top-M'] + + board] 'top-R']) print("--") Prine boa ald-L'] + *|° ¢ boarnid-n'] « *|' + board 'nid-R']) printrss Print boned "LoweL"] + *|* + boar" + beard 'lov8']) printtcard(thetoard) utpat: ro tt "I > The printoard() function can handle any tic-tac-toe data structure you pass it Program ene en set printonreonas) Pcp «i bw er Print(boare( aid] + °[° 4 board nian) *|° + boar wi4-8°]) panes) PreGeaa[‘tovt'] + °1° 4 bed Zoe) + *1* + bat tow peintnthsons) Output: rere xixi ik > Now we created a data structure to represent a tic-tac-toc board and wrote code in printBoard() tointerpret that data structure, we now have a program that “models” the tic > Introduction to Python Programming (BPLCK105B/205B) tac-toe board. Program: allows the players to enter their moves. etoare, Cte def printnoard(ooaré): Brine(poara:op-t'] + ‘1° + boordt'ton-w'h + * Print Cooasd midst") + *[* + board['midsm"} + +] Printers PrineCoosrat Low") 4 | 4 poarel Lowe] + “1° + Bomeat “town 1) for tan ranges): DrineBoarattheseard) Bent Tarn far + tus « '. Move on whieh apace?!) siete + board{ "top-°D) + bowed mta-R*1) Module 2 > The new code prints out the board at the start of each new turn 1, gets the active player's move 2, updates the game board accordingly 3, and then swaps the active player 4 before moving on to the next turn, Nested Dictionaries and Lists > We can have program that contains dictionaries and lists which in turn contain other dictionaries and lists, > Lists are useful to contain an ordered series of values, and dictionaries are useful for associating. keys with values Program: which contains nested dictionaries in order to see who is bringing what to a picnic. ==> ion to Python Programming (BPLCK105B/20SB) Module 2 = (rapples': 5, “pratzels': 42), Bob's (Cham sandwiches’! 3, "apples: 2}, Carol": {(eups' 3, apple’ ples: 1)) Sllmeeste - (UAL def totalBrought guests, ten): rundrought = 0 for ky v in guests tzens(): imeceught + anbrought + v.get(stem, 0) seturn nunfought print(‘hunber of things being bxought:”) Print(: = apples ste (tetalareught(atGunsts, print(* = cups + str(totalBraught alcuests, Drint(’ ~ Cakes + str(totalBreught (allGuests, Drint(’ — fine Sandeiches ° + stz(tetaBreught(sliGuasts, ‘hae zandciches"))) Print(’ — Apple Piss ° + str(totaldreughe(sliGuasts, ‘apple piss"))) > Inside the totalBrought() function, the for loop iterates over the keyvalue pairs in guests 1. > Inside the loop, the string of the guest’s name is assigned to k, and the dictionary of picnic items they’rebringing is assigned to v. > If the item parameter exists as a key in this dictionary, it’s value (the quantity) is added to numBrought 2. > If'it does not exist as a key, the get() method returns 0 to be added to numBrought. Output: Tuber of things being brought = Apples 7 Cope 3 = Cakes © Ham Sordiches 3 = Apple Fies 4

You might also like