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

PP Module 2 - PPT

The document discusses the Python syllabus for the course "Python Programming" covering topics like lists, dictionaries, strings and their methods. It provides an overview of chapters 4-6 in the textbook including the list data type, working with lists using indexes and slices, and manipulating strings. Assignments include projects like a password locker and adding bullets to wiki markup.

Uploaded by

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

PP Module 2 - PPT

The document discusses the Python syllabus for the course "Python Programming" covering topics like lists, dictionaries, strings and their methods. It provides an overview of chapters 4-6 in the textbook including the list data type, working with lists using indexes and slices, and manipulating strings. Assignments include projects like a password locker and adding bullets to wiki markup.

Uploaded by

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

K S Institute of Technology

Department of Artificial Intelligence


and Machine Learning
Python Programming (18AI52)
Academic Year 2022-23 (Odd)
Semester/ Section : 5th A

By:
Dr. Vaneeta M
Associate Professor & Head
Dept. of AIML
KSIT

1
Overview of Syllabus
Module 2:
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, Reference
Dictionaries and Structuring Data, The Dictionary Data Type, Pretty
Printing, Using Data Structures to Model Real-World Things, Manipulating
Strings, Working with Strings, Useful String Methods, Project: Password
Locker, Project: Adding Bullets to Wiki Markup
Textbook 1: Chapters 4 – 6

2
List Chapter 4
Lists and tuples can contain multiple values, which makes
writing programs that handle large amounts of data easier.

Lists,tuple,sets and dictionary are in built data type


available in python

3
List Data Type
• A list is a value that contains multiple values in an
ordered sequence.
• A list value refers to a list itself.
• A list value can be stored as a value to variable or passed
to function as a parameter.
• A list begins with an opening square bracket and ends
with a closing square bracket, []
• Values inside the list are also called items.
• Items are separated with commas
4
List Data Type
>>> [1, 2, 3]
[1, 2, 3]
>>> ['cat', 'bat', 'rat', 'elephant']
['cat', 'bat', 'rat', 'elephant']
>>> ['hello', 3.1415, True, None, 42]
['hello', 3.1415, True, None, 42]
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam
['cat', 'bat', 'rat', 'elephant']
5
List Data Type
Getting Individual Values in a List with 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. 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.
6
List Data Type
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[0]
'cat'
>>> spam[1]
'bat'
>>> spam[2]
'rat'
>>> spam[3]
'elephant’
>>> ['cat', 'bat', 'rat', 'elephant'][3]
'elephant'
➊ >>> 'Hello, ' + spam[0]
➋ 'Hello, cat'
>>> 'The ' + spam[1] + ' ate the ' + spam[0] + '.'
'The bat ate the cat.' 7
List Data Type

Python will give you an IndexError error message if


you use an index that exceeds the number of values
in your list value.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[10000]
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
spam[10000]
IndexError: list index out of range
8
List Data Type
Indexes can be only integer values, not floats. The following example
will cause a TypeError error:
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[1]
'bat'
>>> spam[1.0]
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
spam[1.0]
TypeError: list indices must be integers or slices, not float
>>> spam[int(1.0)]
‘bat’
9
List Data Type

Lists can also contain other list values. The values in


these lists of lists can be accessed using multiple
indexes, like so:
>>> spam = [['cat', 'bat'], [10, 20, 30, 40, 50]]
>>> spam[0]
['cat', 'bat']
>>> spam[0][1]
'bat'
>>> spam[1][4]
50 10
List Data Type
Negative Indexes While indexes start at 0 and go up, you can
also use negative integers for the index. The integer value -1
refers to the last index in a list, the value -2 refers to the
second-to-last index in a list, and so on.
>>> 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.'

11
List Data Type
• Getting a List from Another List with Slices Just as an index
can get a single value from a list, a slice can get several values from
a list, in the form of a new list. A slice is typed between square
brackets, like an index, but it has two integers separated by a colon.
Notice the difference between indexes and slices.
• spam[2] is a list with an index (one integer).
• spam[1:4] is a list with a slice (two integers).
• In a slice, the first integer is the index where the slice starts. The
second integer is the index where the slice ends. A slice goes up to,
but will not include, the value at the second index. A slice valuates
to a new list value.

12
List Data Type

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


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

13
List Data Type
• Getting a List from Another List with Slices As a shortcut, you
can leave out one or both of the indexes on either side of the colon
in the slice.
• Leaving out the first index is the same as using 0, or the beginning of
the list.
• Leaving out the second index is the same as using the length of the
list, which will slice to the end of the list.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[:2]
Lists 81
['cat', 'bat']
>>> spam[1:]
['bat', 'rat', 'elephant’] >>> spam[:]
['cat', 'bat', 'rat', 'elephant'] 14
List Data Type

Getting a List’s Length with the len() Function


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.
Enter the following into the interactive shell:
>>> spam = ['cat', 'dog', 'moose']
>>> len(spam)
3

15
List Data Type

Changing Values in a List with Indexes


Use an index of a list to change the value at that index.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[1] = 'aardvark'
>>> spam
['cat', 'aardvark', 'rat', 'elephant']
>>> spam[2] = spam[1]
>>> spam
['cat', 'aardvark', 'aardvark', 'elephant']
>>> spam[-1] = 12345
>>> spam
['cat', 'aardvark', 'aardvark', 12345]

16
List Data Type

List Concatenation and List Replication


Lists can be concatenated and replicated just like strings. The +
operator combines two lists to create a new list value and the
* operator can be used with a list and an integer value to
replicate the list. Enter the following into the interactive shell:
>>> [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'] 17
List Data Type

Removing Values from Lists with del Statements


The del statement will delete values at an index in a list. All of the
values in the list after the deleted value will be moved up one
index. For example, enter the following into the interactive shell:
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> del spam[2]
>>> spam
['cat', 'bat', 'elephant']
>>> del spam[2]
>>> spam
['cat', 'bat']

18
Working with Lists

catNames = []
while True:
print('Enter the name of cat ' + str(len(catNames) + 1) +
' (Or enter nothing to stop.):’)
name = input()
if name == ‘’:
break
catNames = catNames + [name] # list concatenation
print('The cat names are:')
for name in catNames:
print(' ' + name)

19
Working with Lists

Using for with List


This is because the return value from range(4) is a sequence value
that Python considers similar to [0, 1, 2, 3]. (Sequences are described
in “Sequence Data Types” on page 93.) The following program has
the same output as the previous one:
for i in [0, 1, 2, 3]:
print(i)

20
Working with Lists

>>> supplies = ['pens', 'staplers', 'flamethrowers', 'binders']


>>> for i in range(len(supplies)):
... print('Index ' + str(i) + ' in supplies is: ' + supplies[i])

Index 0 in supplies is: pens


Index 1 in supplies is: staplers
Index 2 in supplies is: flamethrowers
Index 3 in supplies is: binders

21
Working with Lists

The in and not in Operators


You can determine whether a value is or isn’t in a list with the in and not in
operators. Like other operators, in and not in are used in expressions and connect
two values: a value to look for in a list and the list where it may be found. These
expressions will evaluate to a Boolean value. Enter the following
into the interactive shell:
>>> 'howdy' in ['hello', 'hi', 'howdy', 'heyas']
True
>>> spam = ['hello', 'hi', 'howdy', 'heyas']
>>> 'cat' in spam
False
>>> 'howdy' not in spam
False
>>> 'cat' not in spam
True
22
Working with Lists

myPets = ['Zophie', 'Pooka', 'Fat-tail']


print('Enter a pet name:')
name = input()
if name not in myPets:
print('I do not have a pet named ' + name)
else:
print(name + ' is my pet.')

23
Working with Lists
The Multiple Assignment Trick
The multiple assignment trick (technically called tuple
unpacking) is a shortcut that lets you assign multiple variables
with the values in a list in one line of code. So instead of doing
this:
>>> cat = ['fat', 'gray', 'loud']
>>> size = cat[0]
>>> color = cat[1]
>>> disposition = cat[2]
you could type this line of code:
>>> cat = ['fat', 'gray', 'loud']
>>> size, color, disposition = cat
24
Working with Lists

The number of variables and the length of the list


must be exactly equal, or Python will give you a
ValueError:
>>> cat = ['fat', 'gray', 'loud']
>>> size, color, disposition, name = cat
Traceback (most recent call last):
File "<pyshell#84>", line 1, in <module>
size, color, disposition, name = cat
ValueError: not enough values to unpack (expected 4, got 3)

25
Working with Lists

Using the enumerate() Function with Lists


• Instead of using the range(len(someList)) technique with a for loop to
obtain the integer index of the items in the list, you can call the
enumerate() function instead.
• On each iteration of the loop, enumerate() will return two values: the
index of the item in the list, and the item in the list itself.
>>> supplies = ['pens', 'staplers', 'flamethrowers', 'binders']
>>> for index, item in enumerate(supplies):
... print('Index ' + str(index) + ' in supplies is: ' + item)
Index 0 in supplies is: pens
Index 1 in supplies is: staplers
Index 2 in supplies is: flamethrowers
Index 3 in supplies is: binders 26
Working with Lists

Using the random.choice() and random.shuffle() Functions with Lists


The random module has a couple functions that accept lists for
arguments.
The random.choice() function will return a randomly selected item from
the list.
>>> import random
>>> pets = ['Dog', 'Cat', 'Moose']
>>> random.choice(pets)
'Dog'
>>> random.choice(pets)
'Cat'
>>> random.choice(pets)
'Cat'
27
Working with Lists

consider random.choice(someList) to be a shorter form of


someList[random.randint(0, len(someList) – 1].

28
Working with Lists
The random.shuffle() function will reorder the items in a list. This
function modifies the list in place, rather than returning a new list.
>>> import random
>>> people = ['Alice', 'Bob', 'Carol', 'David']
>>> random.shuffle(people)
>>> people
['Carol', 'David', 'Alice', 'Bob']
>>> random.shuffle(people)
>>> people
['Alice', 'David', 'Bob', 'Carol']

29
Augmented Assignment Operators

When assigning a value to a variable, you will frequently use the


variable itself. For example, after assigning 42 to the variable
spam, you would increase the value in spam by 1 with the
following code:
>>> spam = 42
>>> spam = spam + 1
>>> spam
43

>>> spam = 42
>>> spam += 1
>>> spam
43
30
Augmented Assignment Operators

There are augmented assignment operators for the +, -, *, /, and %


operators,

31
Augmented Assignment Operators

The += operator can also do string and list concatenation, and the
*= operator can do string and list replication
>>> spam = 'Hello,'
>>> spam += ' world!'
>>> spam
'Hello world!'
>>> bacon = ['Zophie']
>>> bacon *= 3
>>> bacon
['Zophie', 'Zophie', 'Zophie']

32
Methods
A method is the same thing as a function, except it is
“called on” a value. For example, if a list value were
stored in spam, you would call the index() list method
on that list like so: spam.index('hello').

33
Methods
Finding a Value in a List with the index() Method
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', 'howdy', 'heyas']
>>> spam.index('hello')
0
>>> spam.index('heyas')
3
>>> spam.index('howdy howdy howdy')
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
spam.index('howdy howdy howdy')
ValueError: 'howdy howdy howdy' is not in list
34
Methods

When there are duplicates of the value in the list, the index of
its first appearance is returned. Enter the following into the
interactive shell, and notice that index() returns 1, not 3:
>>> spam = ['Zophie', 'Pooka', 'Fat-tail', 'Pooka']
>>> spam.index('Pooka')
1

35
Methods
Adding Values to Lists with the append() and insert() Methods
To add new values to a list, use the append() and insert() methods.
>>> spam = ['cat', 'dog', 'bat']
>>> spam.append('moose')
>>> spam
['cat', 'dog', 'bat', 'moose']

36
Methods
The insert() method can insert a value at any index in the list.
The first argument to insert() is the index for the new value, and
the second argument is the new value to be inserted. Enter the
following into the interactive shell:
>>> spam = ['cat', 'dog', 'bat']
>>> spam.insert(1, 'chicken')
>>> spam
['cat', 'chicken', 'dog', 'bat']

37
Methods
Notice that the code is spam.append('moose') and spam.insert(1,
'chicken’), not spam = spam.append('moose') and spam = spam.insert(1,
'chicken’).
Neither append() nor insert() gives the new value of spam as its return
value. (In fact, the return value of append() and insert() is None, so you
definitely wouldn’t want to store this as the new variable value.)

38
Methods
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.
>>> eggs = 'hello'
>>> eggs.append('world')
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
eggs.append('world')
AttributeError: 'str' object has no attribute 'append'
>>> bacon = 42
>>> bacon.insert(1, 'world')
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
bacon.insert(1, 'world')
AttributeError: 'int' object has no attribute 'insert'
39
Methods

Removing Values from Lists with the remove() Method


The remove() method is passed the value to be removed from the list it is
called on. Enter the following into the interactive shell:
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam.remove('bat')
>>> spam
['cat', 'rat', 'elephant’]

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


>>> spam.remove('chicken')
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
spam.remove('chicken')
ValueError: list.remove(x): x not in list
40
Methods

If the value appears multiple times in the list, only the first
instance of the value will be removed. Enter the following into
the interactive shell:
>>> spam = ['cat', 'bat', 'rat', 'cat', 'hat', 'cat']
>>> spam.remove('cat')
>>> spam
['bat', 'rat', 'cat', 'hat', '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 useful
when you know the value you want to remove from the list.

41
Methods
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. For
example, enter the following into the interactive shell:
>>> spam = [2, 5, 3.14, 1, -7]
>>> spam.sort()
>>> spam
[-7, 1, 2, 3.14, 5]
>>> spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants']
>>> spam.sort()
>>> spam
['ants', 'badgers', 'cats', 'dogs', 'elephants']

42
Methods
You can also pass True for the reverse keyword argument to have
sort() sort the values in reverse order.
>>> spam.sort(reverse=True)
>>> spam
['elephants', 'dogs', 'cats', 'badgers', 'ants']

43
Methods
There are three things you should note about the sort() method.
1. The sort() method sorts the list in place; don’t try to capture the return value
by writing code like spam = spam.sort().
2. Cannot sort lists that have both number values and string values in them,
>>> spam = [1, 3, 2, 4, 'Alice', 'Bob']
>>> spam.sort()
Traceback (most recent call last):
File "<pyshell#70>", line 1, in <module>
spam.sort()
TypeError: '<' not supported between instances of 'str' and 'int’
3. 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']

44
Methods

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’]
Reversing the Values in a List with the reverse() Method
If you need to quickly reverse the order of the items in a list, you can call the
reverse() list method. Enter the following into the interactive shell:
>>> spam = ['cat', 'dog', 'moose']
>>> spam.reverse()
>>> spam
['moose', 'dog', 'cat']

45
Sequence Data Types
Strings and lists are actually similar if you consider a string to
be a “list” of single text characters.
The Python sequence data types include lists, strings, range
objects returned by range(), and tuples. Many of the things you
can do with lists can also be done with strings and other values
of sequence types: indexing; slicing; and using them with for
loops, with len(), and with the in and not in operators.

46
Sequence Data Types
>>> name = 'Zophie'
>>> name[0]
'Z'
>>> name[-2]
'i'
>>> name[0:4]
'Zoph'
>>> 'Zo' in name
True
>>> 'z' in name
False
>>> 'p' not in name
False
>>> for i in name:
... print('* * * ' + i + ' * * *') 47
Sequence Data Types

Mutable and Immutable Data Types


But lists and strings are different in an important way.
A list value is a mutable data type: it can have values added,
removed, or changed.
A string is immutable: it cannot be changed. Trying to reassign
a single character in a string results in a TypeError error,
>>> name = 'Zophie a cat'
>>> name[7] = 'the'
Traceback (most recent call last):
File "<pyshell#50>", line 1, in <module>
name[7] = 'the'
TypeError: 'str' object does not support item assignment

48
Sequence Data Types

The proper way to “mutate” a string is to use slicing and


concatenation to build a new string by copying from parts of the
old string.
>> name = 'Zophie a cat'
>>> newName = name[0:7] + 'the' + name[8:12]
>>> name
'Zophie a cat'
>>> newName
'Zophie the cat'

49
Sequence Data Types

Although a list value is mutable, the second line in


the following code does not modify the list eggs:
>>> eggs = [1, 2, 3]
>>> eggs = [4, 5, 6]
>>> eggs
[4, 5, 6]

50
Sequence Data Types
If you wanted to actually modify the original list in eggs to
contain [4, 5, 6], you would have to do something like this:
>>> eggs = [1, 2, 3]
>>> del eggs[2]
>>> del eggs[1]
>>> del eggs[0]
>>> eggs.append(4)
>>> eggs.append(5)
>>> eggs.append(6)
>>> eggs
[4, 5, 6]
51
Sequence Data Types

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 ].
>>> eggs = ('hello', 42, 0.5)
>>> eggs[0]
'hello'
>>> eggs[1:3]
(42, 0.5)
>>> len(eggs)
3
52
Sequence Data Types

But 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.
>>> eggs = ('hello', 42, 0.5)
>>> eggs[1] = 99
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
eggs[1] = 99
TypeError: 'tuple' object does not support item assignment

53
Sequence Data Types

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 think you’ve just
typed a value inside regular parentheses. The comma is
what lets Python know this is a tuple value.
>>> type(('hello',))
<class 'tuple'>
>>> type(('hello'))
<class 'str'>

54
Sequence Data Types

• If you need an ordered sequence of values that


never changes, use a tuple.
• A second benefit of using tuples instead of lists is
that, because they are immutable and their
contents don’t change, Python can implement
some optimizations that make code using tuples
slightly faster than code using lists.

55
Sequence Data Types
Converting Types with the list() and tuple() Functions
Just like how str(42) will return '42', the string representation of the
integer 42, the functions list() and tuple() will return list and tuple
versions of the values passed to them.
>>> tuple(['cat', 'dog', 5])
('cat', 'dog', 5)
>>> list(('cat', 'dog', 5))
['cat', 'dog', 5]
>>> list('hello')
['h', 'e', 'l', 'l', 'o']

56
Chapter 5
Dictionaries and Structuring Data

57
The Dictionary Data Type

• Like a list, a dictionary is a mutable collection of


many values.
• But unlike indexes for lists, indexes for
dictionaries can use many different data types,
not just integers.
• Indexes for dictionaries are called keys, and a key
with its associated value is called a key-value pair.

58
The Dictionary Data Type
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:
>>> myCat['size']
'fat'
>>> 'My cat has ' + myCat['color'] + ' fur.'
'My cat has gray fur.'
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.
>>> spam = {12345: 'Luggage Combination', 42: 'The Answer'}

59
The Dictionary Data Type

Dictionaries vs. Lists


• Unlike lists, items in dictionaries are unordered.
• The first item in a list named spam would be spam[0]. But there
is no “first” item in a dictionary.
• While the order of items matters for determining whether two
lists are the same, it does not matter in what order the key-
value pairs are typed in a dictionary.

60
The Dictionary Data Type

>>> 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
True

61
The Dictionary Data Type

Because dictionaries are not ordered, they can’t be sliced like lists.
Trying to access a key that does not exist in a dictionary will result
in a KeyError error message, much like a list’s “out-of-range”
IndexError errormessage.
>>> spam = {'name': 'Zophie', 'age': 7}
>>> spam['color']
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
spam['color']
KeyError: 'color'

62
The Dictionary Data Type
birthdays = {'Alice': 'Apr 1', 'Bob': 'Dec 12', 'Carol': 'Mar 4'}
while True:
print('Enter a name: (blank to quit)’)
name = input()
if name == ‘’:
break
if name in birthdays:
print(birthdays[name] + ' is the birthday of ' + name)
else:
print('I do not have birthday information for ' + name)
print('What is their birthday?’)
bday = input()
birthdays[name] = bday
print('Birthday database updated.') 63
The Dictionary Data Type
Enter a name: (blank to quit)
Alice
Apr 1 is the birthday of Alice
Enter a name: (blank to quit)
Eve
I do not have birthday information for Eve
What is their birthday?
Dec 5
Birthday database updated.
Enter a name: (blank to quit)
Eve
Dec 5 is the birthday of Eve
Enter a name: (blank to quit)

64
The Dictionary Data Type
The keys(), values(), and items() Methods
There are three dictionary methods that will return list-like values of the dictionary’s
keys, values, or both keys and values: keys(), values(), and items().
The values returned by these methods are not true lists: they cannot be modified
and do not have an append() method.
But these data types (dict_keys, dict_values, and dict_items, respectively) can be used
in for loops.
>>> spam = {'color': 'red', 'age': 42}
>>> for v in spam.values():
... print(v)
red
42

65
The Dictionary Data Type

>>> for k in spam.keys():


... print(k)
color
age
>>> for i in spam.items():
... print(i)
('color', 'red')
('age', 42)

66
The Dictionary Data Type

• When you use the keys(), values(), and items() methods, a for
loop can iterate over the keys, values, or key-value pairs in a
dictionary, respectively.
• Notice that the values in the dict_items value returned by the
items() method are tuples of the key and value.
• If you want a true list from one of these methods, pass its list-
like return value to the list() function.
>>> spam = {'color': 'red', 'age': 42}
>>> spam.keys()
dict_keys(['color', 'age'])
>>> list(spam.keys())
['color', 'age']

67
The Dictionary Data Type

You can also use the multiple assignment trick in a for


loop to assign the key and value to separate variables.
>>> spam = {'color': 'red', 'age': 42}
>>> for k, v in spam.items():
... print('Key: ' + k + ' Value: ' + str(v))
Key: age Value: 42
Key: color Value: red

68
The Dictionary Data Type

Checking Whether a Key or Value Exists in a


Dictionary
Recall from the previous chapter that the in and not in
operators can check whether a value exists in a list. into the
interactive shell:
>>> spam = {'name': 'Zophie', 'age': 7}
>>> 'name' in spam.keys()
True
>>> 'Zophie' in spam.values()
True
>>> 'color' in spam.keys()
False
>>> 'color' not in spam.keys()
True
>>> 'color' in spam
False 69
The Dictionary Data Type

The get() Method


It’s tedious to check whether a key exists in a dictionary before
accessing that key’s value. Fortunately, dictionaries have a get()
method that takes two arguments: the key of the value to retrieve
and a fallback value to return if that key does not exist.
>>> picnicItems = {'apples': 5, 'cups': 2}
>>> 'I am bringing ' + str(picnicItems.get('cups', 0)) + ' cups.'
'I am bringing 2 cups.'
>>> 'I am bringing ' + str(picnicItems.get('eggs', 0)) + ' eggs.'
'I am bringing 0 eggs.'

70
The Dictionary Data Type

Without using get(), the code would have caused an error


message, such as in the following example:
>>> picnicItems = {'apples': 5, 'cups': 2}
>>> 'I am bringing ' + str(picnicItems['eggs']) + ' eggs.'
Traceback (most recent call last):
File "<pyshell#34>", line 1, in <module>
'I am bringing ' + str(picnicItems['eggs']) + ' eggs.'
KeyError: 'eggs'

71
The Dictionary Data Type

The setdefault() Method


You’ll often have to set a value in a dictionary for a certain key
only if that key does not already have a value.
spam = {'name': 'Pooka', 'age': 5}
if 'color' not in spam:
spam['color'] = 'black'

72
The Dictionary Data Type
The setdefault() method offers a way to do this in one line of code. 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.
If the key does exist, the setdefault() method returns the key’s value.
>>> spam = {'name': 'Pooka', 'age': 5}
>>> spam.setdefault('color', 'black')
'black'
>>> spam
{'color': 'black', 'age': 5, 'name': 'Pooka'}
>>> spam.setdefault('color', 'white')
'black'
>>> spam
{'color': 'black', 'age': 5, 'name': 'Pooka'}

73
The Dictionary Data Type
• The first time setdefault() is called, the dictionary in spam changes to
{'color': 'black', 'age': 5, 'name': 'Pooka'}. The method returns the value
'black' because this is now the value set for the key 'color’.
• 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’. 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.

74
The Dictionary Data Type

short program that counts the number of occurrences of each letter


in a string
message = 'It was a bright cold day in April, and the clocks were striking
thirteen.'
count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
print(count)

75
The Dictionary Data Type

{' ': 13, ',': 1, '.': 1, 'A': 1, 'I': 1, 'a': 4, 'c': 3, 'b': 1, 'e': 5, 'd': 3, 'g': 2,
'i': 6, 'h': 3, 'k': 2, 'l': 3, 'o': 2, 'n': 4, 'p': 1, 's': 3, 'r': 5, 't': 6, 'w': 2, 'y': 1}

76
The Dictionary Data Type
Pretty Printing
• If you import the pprint module into your programs, you’ll 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.
import pprint
message = 'It was a bright cold day in April, and the clocks were striking
thirteen.'
count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
pprint.pprint(count)

77
The Dictionary Data Type

{' ': 13,


',': 1,
'.': 1,
'A': 1,
'I': 1,
--snip--
't': 6,
'w': 2,
'y': 1}

78
The Dictionary Data Type

• The pprint.pprint() function is especially helpful when the


dictionary itself contains nested lists or dictionaries.
• If you want to obtain the prettified text as a string value
instead of displaying it on the screen, call pprint.pformat()
instead. These two lines are equivalent to each other:
pprint.pprint(someDictionaryValue)
print(pprint.pformat(someDictionaryValue))

79

You might also like