Dictionaries
Dictionaries
– DICTIONARIES - 1
A dictionary is an unordered collection of zero or more key–value pairs whose keys are
object references that refer to hashable objects, and whose values are object references
referring to objects of any type. Dictionaries are mutable, so we can easily add or remove
items, but since they are unordered they have no notion of index position and so cannot be
sliced or strided.
A mapping type is one that supports the membership operator (in) and the size function (len()),
and is iterable. Mappings are collections of key–value items and provide methods for accessing
items and their keys and values. When iterated, unordered mapping types provide their items in
an arbitrary order.
Only hashable objects may be used as dictionary keys, so immutable data types such as float,
frozenset, int, str, and tuple can be used as dictionary keys, but mutable types such as dict, list,
and set cannot. On the other hand, each key’s associated value can be an object reference
referring to an object of any type, including numbers, strings, lists, sets, dictionaries, functions,
and so on.
Dictionary types can be compared using the standard equality comparison operators (== and
!=), with the comparisons being applied item by item (and recursively for nested items such as
tuples or dictionaries inside dictionaries).Comparisons using the other comparison operators
(<, <=, >=, >) are not supported since they don’t make sense for unordered collections such as
dictionaries.
Let’s say you have a list of people. What if you wanted to create a little database where you
could store the telephone numbers of these people:
Once you’ve created these lists, you can look up Cecil’s telephone number as follows:
>>> numbers[names.index('Cecil')]
3158
It works, but it’s a bit impractical. What you really would want to do is something like the
following:
>>> phonebook['Cecil']
3158
DICTIONARY SYNTAX
>>> phonebook = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
>>>days = {'January':31, 'February':28, 'March':31, 'April':30, 'May':31, 'June':30, 'July':31,
'August':31, 'September':30, 'October':31, 'November':30, 'December':31}
More than one entry per key is not allowed. This means no duplicate key is allowed.
When duplicate keys are encountered during assignment, the last assignment wins. For
example-
Keys must be immutable. This means you can use strings, numbers or tuples as
dictionary keys but something like ['key'] is not allowed. Following is a simple example-
Dictionary values have no restrictions. They can be any arbitrary Python object, either standard
objects or user-defined objects.
Unlike in a list, items stored in a dictionary aren’t kept in any particular order.
Unlike Python lists or tuples, the key and value pairs in dictionary objects are not in any
particular order.
Although the key-value pairs are in a certain order in the instantiation statement, by
calling the list method on it (which will create a list from its keys) we can easily see they
aren't stored in that order:
CREATING A DICTIONARY
>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True
Here are some examples to illustrate the various syntaxes—they all produce the same
dictionary:
ASSIGNMENT:
Empty braces: Dictionaries can also be created using braces—empty braces, {}, create an
empty dictionary; nonempty braces must contain one or more commas separated items, each of
which consists of a key, a literal colon, and a value.
>>> dict1 = {}
>>> dict2 = {'name': 'earth', 'port': 80}
Keyword arguments: a sequence of two objects, the first of which is used as a key and the
second of which is used as a value. Alternatively, for dictionaries where the keys are valid
Python identifiers, keyword arguments can be used, with the key as the keyword and the value
as the key’s value.
TYPE CONVERSION:
Dictionaries may also be created using the factory function dict(). You can use the dict
function to construct dictionaries from other mappings (for example, other dictionaries) or
from sequences of (key, value) pairs:
FROM KEYS:
Dictionaries may also be created using a very convenient built-in method for creating a
"default" dictionary whose elements all have the same value (defaulting to None if not given),
fromkeys():
Provided all the key’s values are the same initially, you can also create a dictionary with this
special form—simply pass in a list of keys and an initial value for all of the values (the default
is None):
ZIP()
The built-in zip() function that is used to create dictionary d5 returns a list of tuples, the first of
which has the first items of each of the zip() function’s iterable arguments, the second of which
has the second items, and so on: dict(zip(keyslist, valueslist))
To illustrate, a standard way to initialize a dictionary dynamically in both 2.X and 3.X is to
combine its keys and values with zip, and pass the result to the dict call.
The zip built-in function is the hook that allows us to construct a dictionary from key and value
lists this way—if you cannot predict the set of keys and values in your code, you can always
build them up as lists and zip them together.:
>>> list(zip(['a', 'b', 'c'], [1, 2, 3])) # Zip together keys and values
[('a', 1), ('b', 2), ('c', 3)]
>>> D = dict(zip(['a', 'b', 'c'], [1, 2, 3])) # Make a dict from zip result
>>> D
{'b': 2, 'c': 3, 'a': 1}
>>>
>>>
> > > menu_specials = {}
> > > menu_specials['breakfast'] = 'Canadian ham'
> > > menu_specials['lunch'] = 'tuna surprise'
> > > menu_specials['dinner'] = 'Cheeseburger Deluxe'
> > > print(menu_specials)
{'breakfast': 'Canadian ham', 'lunch': 'tuna surprise', 'dinner': 'Cheeseburger Deluxe'}
> > > menu_specials = {'breakfast' : 'sausage and eggs',
'lunch' : 'split pea soup and garlic bread',
'dinner': '2 hot dogs and onion rings'}
>>>
> > > print(menu_specials)
{'breakfast': 'sausage and eggs', 'lunch': 'split pea soup and garlic bread', 'dinner': '2 hot dogs
and onion rings'}
>>>
> > > print(“%s” % menu_specials[“breakfast”])
sausage and eggs
>>>
>>>
So if we add a key–value item whose key is the same as an existing key, the effect is to
replace that key’s value with a new value.
>>>
>>>dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Mani'}
>>>print ("dict['Name']: ", dict['Name'])
dict['Name']: Mani
>>>
>>>
>>>dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
>>>print ("dict['Name']: ", dict['Name'])
dict['Name']Zara
>>>
>>>print ("dict['Age']: ", dict['Age'])
>>>
dict['Age']7
>>>
If we attempt to access a data item with a key, which is not a part of the dictionary, we get an
error as follows-
Errors for nonexistent key fetches are common in sparse matrixes, but you probably won’t
want them to shut down your program. There are at least three ways to fill in a default value
instead of getting such an error message
>>> Matrix={}
>>> Matrix={(2, 3, 5) : 'T',(2, 4, 8) : 'F'}
>>>
>>> if (2, 3, 6) in Matrix: # Check for key before fetch
print(Matrix[(2, 3, 6)])
else:
print(0)
>>>
0
>>> try:
print(Matrix[(2, 3, 6)]) # Try to index
except KeyError: # Catch and recover
print(0)
>>>
0
>>>
>>> Matrix[(2, 3, 4)]
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
Matrix[(2, 3, 4)]
KeyError: (2, 3, 4)
>>>
>>> Matrix.get((2, 3, 4), 0)
0
>>>
>>> Matrix.get((2, 4, 8), 0)
'F'
>>>
Of these, the get method is the most concise in terms of coding requirements, but the if and try
statements are much more general in scope.
NESTING IN DICTIONARIES.
The following, for example, fills out a dictionary describing a hypothetical person, by
assigning to new keys over time.
>>> rec = {}
>>> rec['name'] = 'Bob'
>>> rec['age'] = 40.5
>>> rec['job'] = 'developer/manager'
>>>
>>> print(rec['name'])
Bob
Especially when nested, Python’s built-in data types allow us to easily represent structured
information.
The following again uses a dictionary to capture object properties, but it codes it all at once
(rather than assigning to each key separately) and nests a list and a dictionary to represent
structured property values:
>>> rec['name']
'Bob'
>>> rec['jobs']
['developer', 'manager']
>>> rec['jobs'][1]
'manager'
>>> rec['home']['zip']
12345
Also notice that we’ve focused on a single “record” with nested data here.
There’s no reason we couldn’t nest the record itself in a larger, enclosing database collection
coded as a list or dictionary, though an external file or formal database interface often plays the
role of top-level container in realistic programs:
>>> db = []
>>> db.append(rec) # A list "database"
>>> db.append(other)
>>> db[0]['jobs']
>>>
>>> db = {}
>>> db['bob'] = rec # A dictionary "database"
>>> db['sue'] = other
>>> db['bob']['jobs']
Notice also the nesting of a list inside a dictionary in this example (the value of the key 'ham').
All collection data types in Python can nest inside each other arbitrarily:
NESTED DICTIONARIES.
For example, here’s a program that uses a dictionary that contains other dictionaries in
order to see who is bringing what to a picnic. The totalBrought() function can read this data
structure and calculate the total number of an item being brought by all the guests.
Inside the totalBrought() function, the for loop iterates over the key-value pairs in
guests.
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.
If the item parameter exists as a key in this dictionary, it’s value (the quantity) is added
to numBrought v.
If it does not exist as a key, the get() method returns 0 to be added to numBrought.
This same totalBrought() function could easily handle a dictionary that contains thousands of
guests, each bringing thousands of different picnic items.Then having this information in a data
structure along with the totalBrought() function would save you a lot of time!
MIXED-VALUE DICTIONARIES
Dictionary values can be any datatype, including integers, Booleans, arbitrary objects, or
even other dictionaries. And within a single dictionary, the values don’t all need to be the same
type; you can mix and match as needed. Dictionary keys are more restricted, but they can be
strings, integers, and a few other types. You can also mix and match key datatypes within a
dictionary.
>>>
>>> SUFFIXES = {1000: ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
1024: ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']}
>>>
>>> len(SUFFIXES)
2
>>>
>>> 1000 in SUFFIXES
True
>>> SUFFIXES[1000]
['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
>>>
>>> SUFFIXES[1024]
['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']
>>>
>>> SUFFIXES[1000][3]
'TB'
>>>
UPDATING DICTIONARY
You can update a dictionary by adding a new entry or a key-value pair, modifying an
existing entry, or deleting an existing entry as shown in a simple example given below.
>>>
>>>dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
>>>dict['Age'] = 8; # update existing entry
>>>dict['School'] = "DPS School" # Add new entry
>>>
>>>print ("dict['Age']: ", dict['Age'])
>>>print ("dict['School']: ", dict['School'])
dict['Age']: 8
dict['School']: DPS School
>>>
Dictionaries do not have any predefined size limit. You can add new key-value pairs to a
dictionary at any time, or you can modify the value of an existing key.
>>>
>>> a_dict={'server': 'db.python3.org', 'database': 'mysql'}
>>> a_dict
{'server': 'db.python3.org', 'database': 'mysql'}
>>>
>>> a_dict['database'] = 'blog'
>>> a_dict
{'server': 'db.python3.org', 'database': 'blog'}
>>>
>>> a_dict['user'] = 'mark'
>>> a_dict
{'server': 'db.python3.org', 'user': 'mark', 'database': 'blog'}
>>>
>>> a_dict['user'] = 'dora'
>>> a_dict
{'server': 'db.python3.org', 'user': 'dora', 'database': 'blog'}
>>>
>>> a_dict['User'] = 'mark'
>>> a_dict
{'User': 'mark', 'server': 'db.python3.org', 'user': 'dora', 'database': 'blog'}
>>>
1. You cannot have duplicate keys in a dictionary. Assigning a value to an existing key will
wipe out the old value.
2. You can add new key-value pairs at any time. This syntax is identical to modifying existing
values.
3. The new dictionary item (key 'user', value 'mark') appears to be in the middle. In fact, it was
just a coincidence that the items appeared to be in order in the first example; it is just as much a
coincidence that they appear to be out of order now.
4. Assigning a value to an existing dictionary key simply replaces the old value with the new
one.
5. Dictionary keys are case-sensitive, so this statement is creating a new key-value pair, not
overwriting an existing one. It may look similar to you, but as far as Python is concerned, it’s
completely different.
You can either remove individual dictionary elements or clear the entire contents of a
dictionary. You can also delete entire dictionary in a single operation. To explicitly remove an
entire dictionary, just use the del statement. del deletes the entry associated with the key
specified as an index.
This produces the following result. Note: An exception is raised because after del dict, the
dictionary does not exist anymore.
dict['Age']:
Traceback (most recent call last):
File "test.py", line 8, in <module>
print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable
>>>
>>> d= {}
>>>
>>> if d:
print("true")
else:
print('false')
false
>>>
>>> d={1:'a'}
>>>
>>> if d:
print("true")
else:
print('false')
true
>>>
>>> if not d: print('D is empty')
>>>
>>> if d: print(d)
{1: 'a'}
>>>
>>>
>>> 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
>>>
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 error message.
Enter the following into the interactive shell, and notice the error message that shows up
because there is no 'color' key:
>>>
>>> spam = {'name': 'Zophie', 'age': 7}
>>> spam['color']
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
spam['color']
KeyError: 'color'
>>>
EXAMPLE: You can use a dictionary with the names as keys and the birthdays as values.
Enter the following code.
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.')
Function Description
cmp(dict1, dict2) No longer available in Python 3
len(dict) Gives the total length of the dictionary. This would be equal to
the number of items in the dictionary.
str(dict) Produces a printable string representation of a dictionary
type(variable) Returns the type of the passed variable. If passed variable is
dictionary, then it would return a dictionary type
Example
The following example shows the usage of len() method.
Length : 3
Example
The following example shows the usage of str() method.
Example
The following example shows the usage of type() method.
Methods Description
dict.clear() Removes all elements of dictionary dict
dict.copy() Returns a shallow copy of dictionary dict
dict.fromkeys() Create a new dictionary with keys from
seq and values set to value
dict.get(key, default=None) For key key, returns value or default if
key not in dictionary
dict.has_key(key) Removed, use the in operation instead
dict.items() Returns a list of dict's (key, value) tuple
pairs
dict.keys() Returns list of dictionary dict's keys
dict.setdefault(key, default=None) Similar to get(), but will set
dict[key]=default if key is not already in
dict
dict.update(dict2) Adds dictionary dict2's key-values pairs
to dict
dict.values() Returns list of dictionary dict's values
Example
The following example shows the usage of clear() method.
Start Len : 2
End Len : 0
Example
The following example shows the usage of copy() method.
Example
The following example shows the usage of fromkeys() method.
Example
The following example shows the usage of get() method.
Value : 27
Value : NA
Example
The following example shows the usage of items() method.
Example
The following example shows the usage of keys() method.
Example
The following example shows the usage of setdefault() method.
Value : 7
Value : None
{'Name': 'Zara', 'Sex': None, 'Age': 7}
Training imparted by: Michael Devine. #8884009669
PROGRAMMING WITH PYTHON 3.6. – DICTIONARIES - 1
Example
The following example shows the usage of update() method.
When we run the above program, it produces the following result updated
Example
The following example shows the usage of values() method.
For reference and preview again, the Table summarizes some of the most common and
representative dictionary operations, and is relatively complete as of Python 3.3.
As usual, though, see the library manual or run a dir(dict) or help(dict) call for a complete list
Operation Interpretation
D = {} Empty dictionary
D = {'name': 'Bob', 'age': 40} Two-item dictionary
E = {'cto': {'name': 'Bob', 'age': Nesting
40}}
D = dict(name='Bob', age=40) Alternative construction techniques:
D = dict([('name', 'Bob'), ('age', keywords,
40)]) key/value pairs,
D = dict(zip(keyslist, valueslist)) zipped key/value pairs,
D = dict.fromkeys(['name', 'age']) key lists
D['name'] Indexing by key
E['cto']['age'] 'age' in D Membership: key present test
D.keys() Methods:
D.values() all keys,
D.items() all values,
D.copy() all key+value tuples,
D.clear() copy (top-level),
D.update(D2) clear (remove all items),
D.get(key, default?) merge by keys,
D.pop(key, default?) fetch by key, if absent default (or None),
D.setdefault(key, default?) remove by key, if absent default (or error)
D.popitem() fetch by key, if absent set default (or None),
remove/return any (key, value) pair; etc.
len(D) Length: number of stored entries
D[key] = 42 Adding/changing keys
del D[key] Deleting entries by key
list(D.keys()) Dictionary views (Python 3.X)
D1.keys()
D2.keys()
D.viewkeys(), Dictionary views (Python 2.7)
D.viewvalues()
D = {x: x*2 for x in range(10)} Dictionary comprehensions (Python 3.X, 2.7)
EXERCISE.
A Tic-Tac-Toe Board
A tic-tac-toe board looks like a large hash symbol (#) with nine slots that can each contain an
X, an O, or a blank.
To represent the board with a dictionary, you can assign each slot a string-value key, as shown
in the Figure.
You can use string values to represent what’s in each slot on the board: 'X', 'O', or ' ' (a space
character). Thus, you’ll need to store nine strings. You 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.
This dictionary is a data structure that represents a tic-tac-toe board. Store this board-as-a-
dictionary in a variable named theBoard. Open a new file editor window, and enter the
following source code, saving it as ticTacToe.py:
The data structure stored in the theBoard variable represents the tic-tac-toe board in Figure.
theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ',
'mid-L': ' ', 'mid-M': ' ', 'mid-R': ' ',
'low-L': ' ', 'low-M': ' ', 'low-R': ' '}
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:
theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ',
'mid-L': ' ', 'mid-M': 'X', 'mid-R': ' ',
'low-L': ' ', 'low-M': ' ', 'low-R': ' '}
The data structure in theBoard now represents the tic-tac-toe board in Figure.
A board where player O has won by placing Os across the top might look like this:
The data structure in theBoard now represents the tic-tac-toe board in Figure. Player O wins
O O O
X X
X
Let’s create a function to print the board dictionary onto the screen.
theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ','mid-L': ' ', 'mid-M': ' ', 'mid-R': ' ',
'low-L': ' ', 'low-M': ' ', 'low-R': ' '}
def printBoard(board):
print(board['top-L'] + '|' + board['top-M'] + '|' + board['top-R'])
print('-+-+-')
printBoard(theBoard)
When you run this program, printBoard() will print out a blank tic-tactoe board.
||
-+-+-
||
-+-+-
||
The printBoard() function can handle any tic-tac-toe data structure you pass it. Try changing
the code to the following:
theBoard = {'top-L': 'O', 'top-M': 'O', 'top-R': 'O', 'mid-L': 'X', 'mid-M':'X', 'mid-R': ' ',
'low-L': ' ', 'low-M': ' ', 'low-R': 'X'}
def printBoard(board):
print(board['top-L'] + '|' + board['top-M'] + '|' + board['top-R'])
print('-+-+-')
print(board['mid-L'] + '|' + board['mid-M'] + '|' + board['mid-R'])
print('-+-+-')
print(board['low-L'] + '|' + board['low-M'] + '|' + board['low-R'])
printBoard(theBoard)
Now when you run this program, the new board will be printed to the screen.
O|O|O
-+-+-
X|X|
-+-+-
| |X
Because you created a data structure to represent a tic-tac-toe board and wrote code in
printBoard() to interpret that data structure, you now have a program that “models” the tic-tac-
toe board. You could have organized your data structure differently (for example, using keys
like 'TOP-LEFT' instead of 'top-L'), but as long as the code works with your data structures,
you will have a correctly working program. For example, the printBoard() function expects the
tic-tac-toe data structure to be a dictionary with keys for all nine slots. If the dictionary you
passed was missing, say, the 'mid-L' key, your program would no longer work.
O|O|O
-+-+-
Traceback (most recent call last):
File "ticTacToe.py", line 10, in <module>
printBoard(theBoard)
File "ticTacToe.py", line 6, in printBoard
print(board['mid-L'] + '|' + board['mid-M'] + '|' + board['mid-R'])
KeyError: 'mid-L'
Training imparted by: Michael Devine. #8884009669
PROGRAMMING WITH PYTHON 3.6. – DICTIONARIES - 1
Now let’s add code that allows the players to enter their moves. Modify the ticTacToe.py
program to look like this:
theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ', 'mid-L': ' ', 'mid-M': '', 'mid-R': ' ',
'low-L': ' ', 'low-M': ' ', 'low-R': ' '}
def printBoard(board):
print(board['top-L'] + '|' + board['top-M'] + '|' + board['top-R'])
print('-+-+-')
turn = 'X'
for i in range(9):
printBoard(theBoard)
print('Turn for ' + turn + '. Move on which space?')
move = input()
theBoard[move] = turn
if turn == 'X':
turn = 'O'
else:
turn = 'X'
printBoard(theBoard)
The new code prints out the board at the start of each new turn u, gets the active player’s move
v, updates the game board accordingly w, and then swaps the active player x before moving on
to the next turn.
When you run this program, it will look something like this:
||
-+-+-
||
-+-+-
||
Turn for X. Move on which space?
mid-M
||
-+-+-
|X|
-+-+-
||
Turn for O. Move on which space?
low-L
||
-+-+-
|X|
-+-+-
O| |
------
------
------
------
O|O|X
-+-+-
X|X|O
-+-+-
O| |X
Turn for X. Move on which space?
low-M
O|O|X
-+-+-
X|X|O
-+-+-
O|X|X
The program displays a menu that allows the user to make one of the following choices:
1. Look up a birthday
2. Add a new birthday
3. Change a birthday
4. Delete a birthday
5. Quit the program
The program initially starts with an empty dictionary, so you have to:
choose item 2 from the menu to add a new entry.
Rather than presenting the entire program at once, let’s first examine the global constants and
the main function:
The global constants that are declared in lines 5 through 9 are used to test the user’s menu
selection.
Inside the main function, line 14 creates an empty dictionary referenced by the birthdays
variable.
Line 17 initializes the choice variable with the value 0. This variable holds the user’s menu
selection.
The while loop that begins in line 19 repeats until the user chooses to quit the program.
Training imparted by: Michael Devine. #8884009669
PROGRAMMING WITH PYTHON 3.6. – DICTIONARIES - 1
Inside the loop, line 21 calls the get_menu_choice function. The get_menu_choice function
displays the menu and returns the user’s selection. The value that is returned is assigned
to the choice variable.
The if-elif statement in lines 24 through 31 processes the user’s menu choice.
If the user selects item 1, line 25 calls the look_up function.
If the user selects item 2, line 27 calls the add function.
If the user selects item 3, line 29 calls the change function.
If the user selects item 4, line 31 calls the delete function.
Line 47 prompts the user to enter his or her choice. The input is converted to an int and
assigned to the choice variable. The while loop in lines 50 through 51 validates the user’s input
and, if necessary, prompts the user to reenter his or her choice.
Once a valid choice is entered, it is returned from the function in line 54.
The purpose of the look_up function is to allow the user to look up a friend’s birthday. It
accepts the dictionary as an argument.
Line 60 prompts the user to enter a name, and line 63 passes that name as an argument to the
dictionary’s get function. If the name is found, its associated value (the friend’s birthday) is
returned and displayed. If the name is not found, the string ‘Not found.’ is displayed.
The purpose of the add function is to allow the user to add a new birthday to the dictionary.
It accepts the dictionary as an argument. Lines 69 and 70 prompt the user to enter a name
and a birthday.
The if statement in line 73 determines whether the name is not already in the dictionary. If not,
line 74 adds the new name and birthday to the dictionary. Otherwise, a message indicating that
the entry already exists is printed in line 76.
The purpose of the change function is to allow the user to change an existing birthday in
the dictionary. It accepts the dictionary as an argument.
The if statement in line 84 determines whether the name is in the dictionary. If so, line 86
gets the new birthday, and line 89 stores that birthday in the dictionary. If the name is not
in the dictionary, line 91 prints a message indicating so.
The purpose of the delete function is to allow the user to delete an existing birthday from
the dictionary. It accepts the dictionary as an argument.
The if statement in line 100 determines whether the name is in the dictionary. If so, line
101 deletes it. If the name is not in the dictionary, line 103 prints a message indicating so.
ASSIGNMENT:
1. Scrabble Score: In the game of Scrabble™, each letter has points associated with it. The
total score of a word is the sum of the scores of its letters. More common letters are worth
fewer points while less common letters are worth more points. The points associated with each
letter are shown below:
Write a program that computes and displays the Scrabble™ score for a word.
Create a dictionary that maps from letters to point values. Then use the dictionary to compute
the score.
2. Text Messaging: On some basic cell phones, text messages can be sent using the numeric
keypad. Because each key has multiple letters associated with it, multiple key presses are
needed for most letters. Pressing the number once generates the first letter on the key. Pressing
the number 2, 3, 4 or 5 times will generate the second, third, fourth or fifth character listed for
that key.
Key Symbols
1 .,?!:
2 ABC
3 DEF
4 GHI
5 JKL
6 MNO
7 PQRS
8 TUV
9 WXYZ
0 space
Write a program that displays the key presses that must be made to enter a text message read
from the user. Construct a dictionary that maps from each letter or symbol to the key presses.
Then use the dictionary to generate and display the presses for the user’s message.
For example, if the user enters “Hello, World!” then your program should output:
4433555555666110966677755531111. Ensure that your program handles both uppercase and
lowercase letters. Ignore any characters that aren’t listed in the table above such as semicolons
and brackets.
Training imparted by: Michael Devine. #8884009669