[go: up one dir, main page]

0% found this document useful (0 votes)
25 views38 pages

Dictionaries

The document discusses dictionaries in Python, including how to create dictionaries with various syntax, properties of dictionary keys such as being unique and immutable, converting between dictionaries and lists, and examples of creating dictionaries.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views38 pages

Dictionaries

The document discusses dictionaries in Python, including how to create dictionaries with various syntax, properties of dictionary keys such as being unique and immutable, converting between dictionaries and lists, and examples of creating dictionaries.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

PROGRAMMING WITH PYTHON 3.6.

– 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:

>>> names = ['Alice', 'Beth', 'Cecil', 'Dee-Dee', 'Earl']


>>> numbers = ['2341', '9102', '3158', '0142', '5551']

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

Guess what? If phonebook is a dictionary, you can do just that.

>>>phonebook = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}

Training imparted by: Michael Devine. #8884009669


PROGRAMMING WITH PYTHON 3.6. – DICTIONARIES - 1

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}

Properties of Dictionary Keys

There are two important points to remember about dictionary keys-

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

>>>dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Mani'}


>>>print ("dict['Name']: ", dict['Name'])
dict['Name']: Mani

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

>>>dict = {['Name']: 'Zara', 'Age': 7}


>>>print ("dict['Name']: ", dict['Name'])
Traceback (most recent call last):
File "test.py", line 3, in <module>
dict = {['Name']: 'Zara', 'Age': 7}
TypeError: list objects are unhashable

Dictionary values have no restrictions. They can be any arbitrary Python object, either standard
objects or user-defined objects.

DICTIONARY VALUES ARE NOT STORED IN SORTED ORDER.

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

Training imparted by: Michael Devine. #8884009669


PROGRAMMING WITH PYTHON 3.6. – DICTIONARIES - 1

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:

>>>d1 = dict({"id": 1948, "name": "Washer", "size": 3})


>>>d2 = dict(id=1948, name="Washer", size=3)
>>>d3 = dict([("id", 1948), ("name", "Washer"), ("size", 3)])
>>>d4 = {"id": 1948, "name": "Washer", "size": 3}

Dictionary d1 is created using a dictionary literal.


Dictionary d2 is created using keyword arguments.
Dictionaries d3 are created from sequences,
Dictionary d4 is created by assignment

ASSIGNMENT:

Creating dictionaries simply involves assigning a dictionary to a variable, regardless of


whether the dictionary has elements or not:

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.

>>> dict3 = {'name'= 'mars', 'port'= 82}


>>> dict1, dict2, dict3
({}, {'port': 80, 'name': 'earth'}, {'port': 82, 'name': 'mars'})

Training imparted by: Michael Devine. #8884009669


PROGRAMMING WITH PYTHON 3.6. – DICTIONARIES - 1

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:

>>> items = [('name', 'Gumby'), ('age', 42)]


>>> d = dict(items)
>>> d
{'age': 42, 'name': 'Gumby'}
>>> d['name']
'Gumby'
>>> items = ['name', 'Gumby', 'age', 42]
>>> e = dict(items)
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
e = dict(items)
ValueError: dictionary update sequence element #0 has length 4; 2 is required
>>>
>>> items = [['name', 'Gumby'], ['age', 42]]
>>> e = dict(items)
>>> e
{'name': 'Gumby', 'age': 42}

It can also be used with keyword arguments, as follows:

>>> d = dict(name='Gumby', age=42)


>>> d
{'age': 42, 'name': 'Gumby'}
>>> fdict = dict((['x', 1], ['y', 2]))
>>> fdict
{'y': 2, 'x': 1}

Converting a Dictionary to a list will give a list of keys.

>>> numbers = {'first': 1, 'second': 2, 'third': 3, 'Fourth': 4}


>>> numbers
{'first': 1, 'second': 2, 'third': 3, 'Fourth': 4}
>>> list(numbers)
['first', 'second', 'third', 'Fourth']

Training imparted by: Michael Devine. #8884009669


PROGRAMMING WITH PYTHON 3.6. – DICTIONARIES - 1

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():

>>> ddict = {}.fromkeys(('x', 'y'), -1)


>>> ddict
{'y': -1, 'x': -1}
>>>
>>> edict = {}.fromkeys(('foo', 'bar'))
>>> edict
{'foo': None, 'bar': None}

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

>>> dict.fromkeys(['a', 'b'], 0)


{'a': 0, 'b': 0}

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

>>>d5 = dict(zip(("id", "name", "size"), (1948, "Washer", 3)))

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

Training imparted by: Michael Devine. #8884009669


PROGRAMMING WITH PYTHON 3.6. – DICTIONARIES - 1

EXAMPLE OF CREATING A DICTIONARY:

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

DICTIONARY KEYS ARE UNIQUE:

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

Training imparted by: Michael Devine. #8884009669


PROGRAMMING WITH PYTHON 3.6. – DICTIONARIES - 1

ACCESSING VALUES IN DICTIONARY


To access dictionary elements, you can use the familiar square brackets along with the key to
obtain its value.

Following is a simple example.

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

>>>dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};


>>>print( "dict['Alice']: ", dict['Alice'] )
Traceback (most recent call last):
print( "dict['Alice']: ", dict['Alice']);
KeyError: 'Alice'

Training imparted by: Michael Devine. #8884009669


PROGRAMMING WITH PYTHON 3.6. – DICTIONARIES - 1

AVOIDING MISSING-KEY ERRORS

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

 you can test for keys ahead of time in if statements,


 use a try statement to catch and recover from the exception explicitly
 use the dictionary get method shown earlier to provide a default for keys that do not
exist.

Consider the first two of these previews for statement syntax:

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

Training imparted by: Michael Devine. #8884009669


PROGRAMMING WITH PYTHON 3.6. – DICTIONARIES - 1

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


'jobs': ['developer', 'manager'],
'web': 'www.bobs.org/˜Bob',
'home': {'state': 'Overworked', 'zip': 12345}}

To fetch components of nested objects, simply string together indexing operations:

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

Training imparted by: Michael Devine. #8884009669


PROGRAMMING WITH PYTHON 3.6. – DICTIONARIES - 1

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:

>>> D={'eggs': 3, 'spam': 2, 'ham': 1}


>>> D
{'eggs': 3, 'spam': 2, 'ham': 1}
>>> D['ham'] = ['grill', 'bake', 'fry'] # Change entry (value=list)
>>> D
{'eggs': 3, 'spam': 2, 'ham': ['grill', 'bake', 'fry']}
>>> del D['eggs'] # Delete entry
>>> D
{'spam': 2, 'ham': ['grill', 'bake', 'fry']}
>>> D['brunch'] = 'Bacon' # Add new entry
>>> D
{'brunch': 'Bacon', 'spam': 2, 'ham': ['grill', 'bake', 'fry']}

Training imparted by: Michael Devine. #8884009669


PROGRAMMING WITH PYTHON 3.6. – DICTIONARIES - 1

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.

allGuests = {'Alice': {'apples': 5, 'pretzels': 12},


'Bob': {'ham sandwiches': 3, 'apples': 2},
'Carol': {'cups': 3, 'apple pies': 1}
}

def totalBrought(guests, item):


numBrought = 0
for k, v in guests.items():
numBrought = numBrought + v.get(item, 0)
return numBrought

print('Number of things being brought:')


print(' - Apples ' + str(totalBrought(allGuests, 'apples')))
print(' - Cups ' + str(totalBrought(allGuests, 'cups')))
print(' - Cakes ' + str(totalBrought(allGuests, 'cakes')))
print(' - Ham Sandwiches ' + str(totalBrought(allGuests, 'ham sandwiches')))
print(' - Apple Pies ' + str(totalBrought(allGuests, 'apple pies')))

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

The output of this program looks like this:

Number of things being brought:


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

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!

Training imparted by: Michael Devine. #8884009669


PROGRAMMING WITH PYTHON 3.6. – DICTIONARIES - 1

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

 The len() function gives you the number of keys in a dictionary.


 You can use the in operator to test whether a specific key is defined in a dictionary.
 1000 is a key in the SUFFIXES dictionary; its value is a list of eight items (eight strings,
to be precise).
 Similarly, 1024 is a key in the SUFFIXES dictionary; its value is also a list of eight
items.
 Since SUFFIXES[1000] is a list, you can address individual items in the list by their 0-
based index.

Training imparted by: Michael Devine. #8884009669


PROGRAMMING WITH PYTHON 3.6. – DICTIONARIES - 1

CHANGING DICTIONARIES IN PLACE


Dictionaries, like lists, are mutable, so you can change, expand, and shrink them in place
without making new dictionaries: simply assign a value to a key to change or create an entry.

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

Training imparted by: Michael Devine. #8884009669


PROGRAMMING WITH PYTHON 3.6. – DICTIONARIES - 1

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.

DELETE DICTIONARY ELEMENTS

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.

Following is a simple example-

>>>dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}


>>>del dict['Name'] # remove entry with key 'Name'
>>>dict.clear() # remove all entries in dict
>>>del dict # delete entire dictionary
>>>
>>>print ("dict['Age']: ", dict['Age'])
>>>print ("dict['School']: ", dict['School'])

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

Training imparted by: Michael Devine. #8884009669


PROGRAMMING WITH PYTHON 3.6. – DICTIONARIES - 1

DICTIONARIES IN A BOOLEAN CONTEXT

You can also use a dictionary in a Boolean context, such as an if statement.

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

1. In a Boolean context, an empty dictionary is false.


2. Any dictionary with at least one key-value pair is true.

Training imparted by: Michael Devine. #8884009669


PROGRAMMING WITH PYTHON 3.6. – DICTIONARIES - 1

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.

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

Training imparted by: Michael Devine. #8884009669


PROGRAMMING WITH PYTHON 3.6. – DICTIONARIES - 1

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

 You create an initial dictionary and store it in birthday.


 You can see if the entered name exists as a key in the dictionary with the in keyword,
just as you did for lists.
 If the name is in the dictionary, you access the associated value using square brackets;
 If not, you can add it using the same square bracket syntax combined with the
assignment operator.
 When you run this program, it will look like this:

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)

Training imparted by: Michael Devine. #8884009669


PROGRAMMING WITH PYTHON 3.6. – DICTIONARIES - 1

Built-in Dictionary Functions & Methods


Python includes the following dictionary functions-

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

Dictionary len() Method


Description
The method len() gives the total length of the dictionary. This would be equal to the
number of items in the dictionary.

Example
The following example shows the usage of len() method.

dict = {'Name': 'Manni', 'Age': 7, 'Class': 'First'}


print ("Length : %d" % len (dict))

When we run the above program, it produces the following result-

Length : 3

Dictionary str() Method


Description
The method str() produces a printable string representation of a dictionary.

Example
The following example shows the usage of str() method.

dict = {'Name': 'Manni', 'Age': 7, 'Class': 'First'}


print ("Equivalent String : %s" % str (dict))

When we run the above program, it produces the following result-

Equivalent String : {'Name': 'Manni', 'Age': 7, 'Class': 'First'}

Training imparted by: Michael Devine. #8884009669


PROGRAMMING WITH PYTHON 3.6. – DICTIONARIES - 1

Dictionary type() Method


Description
The method type() 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 type() method.

dict = {'Name': 'Manni', 'Age': 7, 'Class': 'First'}


print ("Variable Type : %s" % type (dict))

When we run the above program, it produces the following result-

Variable Type : <type 'dict'>

PYTHON INCLUDES THE FOLLOWING DICTIONARY METHODS.

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

Training imparted by: Michael Devine. #8884009669


PROGRAMMING WITH PYTHON 3.6. – DICTIONARIES - 1

Dictionary clear() Method


Description
The method clear() removes all items from the dictionary.

Example
The following example shows the usage of clear() method.

dict = {'Name': 'Zara', 'Age': 7}


print ("Start Len : %d" % len(dict))
dict.clear()
print ("End Len : %d" % len(dict))

When we run the above program, it produces the following result-

Start Len : 2
End Len : 0

Dictionary copy() Method


Description
The method copy() returns a shallow copy of the dictionary.

Example
The following example shows the usage of copy() method.

dict1 = {'Name': 'Mani', 'Age': 7, 'Class': 'First'}


dict2 = dict1.copy()
print ("New Dictionary : ",dict2)

When we run the above program, it produces following result-

New dictionary : {'Name': 'Mani', 'Age': 7, 'Class': 'First'}

Training imparted by: Michael Devine. #8884009669


PROGRAMMING WITH PYTHON 3.6. – DICTIONARIES - 1

Dictionary fromkeys() Method


Description
The method fromkeys() creates a new dictionary with keys from seq and values set to value.

Example
The following example shows the usage of fromkeys() method.

seq = ('name', 'age', 'sex')


dict = dict.fromkeys(seq)
print ("New Dictionary : %s" % str(dict))
dict = dict.fromkeys(seq, 10)
print ("New Dictionary : %s" % str(dict))

When we run the above program, it produces the following result-

New Dictionary : {'age': None, 'name': None, 'sex': None}


New Dictionary : {'age': 10, 'name': 10, 'sex': 10}

Dictionary get() Method


Description
The method get() returns a value for the given key. If the key is not available then returns
default value None.

Example
The following example shows the usage of get() method.

dict = {'Name': 'Zara', 'Age': 27}


print ("Value : %s" % dict.get('Age'))
print ("Value : %s" % dict.get('Sex', "NA"))

When we run the above program, it produces the following result-

Value : 27
Value : NA

Training imparted by: Michael Devine. #8884009669


PROGRAMMING WITH PYTHON 3.6. – DICTIONARIES - 1

Dictionary items() Method


Description
The method items() returns a list of dict's (key, value) tuple pairs.

Example
The following example shows the usage of items() method.

dict = {'Name': 'Zara', 'Age': 7}


print ("Value : %s" % dict.items())

When we run the above program, it produces the following result-

Value : [('Age', 7), ('Name', 'Zara')]

Dictionary keys() Method


Description
The method keys() returns a list of all the available keys in the dictionary.

Example
The following example shows the usage of keys() method.

dict = {'Name': 'Zara', 'Age': 7}


print ("Value : %s" % dict.keys())

When we run the above program, it produces the following result-

Value : ['Age', 'Name']

Dictionary setdefault() Method


Description
Similar to get(), but will set dict[key]=default if the key is not already in dict.

Example
The following example shows the usage of setdefault() method.

dict = {'Name': 'Zara', 'Age': 7}


print ("Value : %s" % dict.setdefault('Age', None))
print ("Value : %s" % dict.setdefault('Sex', None))
print (dict)

When we run the above program, it produces the following result-

Value : 7
Value : None
{'Name': 'Zara', 'Sex': None, 'Age': 7}
Training imparted by: Michael Devine. #8884009669
PROGRAMMING WITH PYTHON 3.6. – DICTIONARIES - 1

Dictionary update() Method


Description
The method update() adds dictionary dict2's key-values pairs in to dict. This function does not
return anything.

Example
The following example shows the usage of update() method.

dict = {'Name': 'Zara', 'Age': 7}


dict2 = {'Sex': 'female' }
dict.update(dict2)
print ("updated dict : ", dict)

When we run the above program, it produces the following result updated

dict : {'Sex': 'female', 'Age': 7, 'Name': 'Zara'}

Dictionary values() Method


Description
The method values() returns a list of all the values available in a given dictionary.

Example
The following example shows the usage of values() method.

dict = {'Sex': 'female', 'Age': 7, 'Name': 'Zara'}


print ("Values : ", list(dict.values()))

When we run above program, it produces following result-

Values : ['female', 7, 'Zara']

Training imparted by: Michael Devine. #8884009669


PROGRAMMING WITH PYTHON 3.6. – DICTIONARIES - 1

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)

Training imparted by: Michael Devine. #8884009669


PROGRAMMING WITH PYTHON 3.6. – DICTIONARIES - 1

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.

'top-L' 'top-M' 'top-R'


'mid-L' 'mid-M' 'mid-R'
'low-L' 'low-M' 'low-R'

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.

Figure: An empty tic-tac-toe board

Training imparted by: Michael Devine. #8884009669


PROGRAMMING WITH PYTHON 3.6. – DICTIONARIES - 1

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:

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

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.

Make the following addition to ticTacToe.py (new code is in bold):

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

def printBoard(board):
print(board['top-L'] + '|' + board['top-M'] + '|' + board['top-R'])
print('-+-+-')

print(board['mid-L'] + '|' + board['mid-M'] + '|' + board['mid-R'])


print('-+-+-')

print(board['low-L'] + '|' + board['low-M'] + '|' + board['low-R'])

printBoard(theBoard)

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

Training imparted by: Michael Devine. #8884009669


PROGRAMMING WITH PYTHON 3.6. – DICTIONARIES - 1

||
-+-+-
||
-+-+-
||

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

print(board['mid-L'] + '|' + board['mid-M'] + '|' + board['mid-R'])


print('-+-+-')

print(board['low-L'] + '|' + board['low-M'] + '|' + board['low-R'])

turn = 'X'
for i in range(9):
printBoard(theBoard)
print('Turn for ' + turn + '. Move on which space?')

move = input()
theBoard[move] = turn

if turn == 'X':
turn = 'O'
else:
turn = 'X'

printBoard(theBoard)

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.

Training imparted by: Michael Devine. #8884009669


PROGRAMMING WITH PYTHON 3.6. – DICTIONARIES - 1

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

Training imparted by: Michael Devine. #8884009669


PROGRAMMING WITH PYTHON 3.6. – DICTIONARIES - 1

Storing Names and Birthdays in a Dictionary


In this exercise we look at a program that keeps your friends’ names and birthdays in a
dictionary. Each entry in the dictionary uses a friend’s name as the key and that friend’s
birthday as the value. You can use the program to look up your friends’ birthdays by entering
their names.

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.

Once you have added a few entries, you can:


 choose item 1 to look up a specific person’s birthday,
 item 3 to change an existing birthday in the dictionary,
 item 4 to delete a birthday from the dictionary, or
 item 5 to quit the program.

The Program shows the program code.


The program is divided into six functions:
 main,
 get_menu_choice,
 look_up,
 add, change, and
 delete.

Rather than presenting the entire program at once, let’s first examine the global constants and
the main function:

Training imparted by: Michael Devine. #8884009669


PROGRAMMING WITH PYTHON 3.6. – DICTIONARIES - 1

Program (birthdays.py: main function)

1 # This program uses a dictionary to keep friends'


2 # names and birthdays.
3
4 # Global constants for menu choices
5 LOOK_UP = 1
6 ADD = 2
7 CHANGE = 3
8 DELETE = 4
9 QUIT = 5
10
11 # main function
12 def main():
13 # Create an empty dictionary.
14 birthdays = {}
15
16 # Initialize a variable for the user's choice.
17 choice = 0
18
19 while choice != QUIT:
20 # Get the user's menu choice.
21 choice = get_menu_choice()
22
23 # Process the choice.
24 if choice == LOOK_UP:
25 look_up(birthdays)
26 elif choice == ADD:
27 add(birthdays)
28 elif choice == CHANGE:
29 change(birthdays)
30 elif choice == DELETE:
31 delete(birthdays)
32

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.

The get_menu_choice function is next.


Program (birthdays.py: get_menu_choice function)

33 # The get_menu_choice function displays the menu


34 # and gets a validated choice from the user.
35 def get_menu_choice():
36 print()
37 print('Friends and Their Birthdays')
38 print('---------------------------')
39 print('1. Look up a birthday')
40 print('2. Add a new birthday')
41 print('3. Change a birthday')
42 print('4. Delete a birthday')
43 print('5. Quit the program')
44 print()
45
46 # Get the user's choice.
47 choice = int(input('Enter your choice: '))
48
49 # Validate the choice.
50 while choice < LOOK_UP or choice > QUIT:
51 choice = int(input('Enter a valid choice: '))
52
53 # return the user's choice.
54 return choice
55

The statements in lines 36 through 44 display the menu on the screen.

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.

Training imparted by: Michael Devine. #8884009669


PROGRAMMING WITH PYTHON 3.6. – DICTIONARIES - 1

The look_up function is next.


Program (birthdays.py: look_up function)

56 # The look_up function looks up a name in the


57 # birthdays dictionary.
58 def look_up(birthdays):
59 # Get a name to look up.
60 name = input('Enter a name: ')
61
62 # Look it up in the dictionary.
63 print(birthdays.get(name, 'Not found.'))
64

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 add function is next.


Program (birthdays.py: add function)

65 # The add function adds a new entry into the


66 # birthdays dictionary.
67 def add(birthdays):
68 # Get a name and birthday.
69 name = input('Enter a name: ')
70 bday = input('Enter a birthday: ')
71
72 # If the name does not exist, add it.
73 if name not in birthdays:
74 birthdays[name] = bday
75 else:
76 print('That entry already exists.')
77

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.

Training imparted by: Michael Devine. #8884009669


PROGRAMMING WITH PYTHON 3.6. – DICTIONARIES - 1

The change function is next.


Program (birthdays.py: change function)

78 # The change function changes an existing


79 # entry in the birthdays dictionary.
80 def change(birthdays):
81 # Get a name to look up.
82 name = input('Enter a name: ')
83
84 if name in birthdays:
85 # Get a new birthday.
86 bday = input('Enter the new birthday: ')
87
88 # Update the entry.
89 birthdays[name] = bday
90 else:
91 print('That name is not found.')
92

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.

Line 82 gets a name from the user.

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 delete function is next.


Program (birthdays.py: change function)

93 # The delete function deletes an entry from the


94 # birthdays dictionary.
95 def delete(birthdays):
96 # Get a name to look up.
97 name = input('Enter a name: ')
98
99 # If the name is found, delete the entry.
100 if name in birthdays:
101 del birthdays[name]
102 else:
103 print('That name is not found.')
104
105 # Call the main function.
106 main()
Training imparted by: Michael Devine. #8884009669
PROGRAMMING WITH PYTHON 3.6. – DICTIONARIES - 1

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.

Line 97 gets a name from the user.

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.

Program Output (with input shown in bold)

Friends and Their Birthdays


---------------------------
1. Look up a birthday
2. Add a new birthday
3. Change a birthday
4. Delete a birthday
5. Quit the program

Enter your choice: 2 enter


Enter a name: Cameron enter
Enter a birthday: 10/12/1990
enter

Friends and Their Birthdays


---------------------------
1. Look up a birthday
2. Add a new birthday
3. Change a birthday
4. Delete a birthday
5. Quit the program

Enter your choice: 2 enter


Enter a name: Kathryn enter
Enter a birthday: 5/7/1989 enter

Friends and Their Birthdays


---------------------------
1. Look up a birthday
2. Add a new birthday
3. Change a birthday
4. Delete a birthday
5. Quit the program

Enter your choice: 1 enter


Enter a name: Cameron
enter
10/12/1990
Training imparted by: Michael Devine. #8884009669
PROGRAMMING WITH PYTHON 3.6. – DICTIONARIES - 1

Friends and Their Birthdays


---------------------------
1. Look up a birthday
2. Add a new birthday
3. Change a birthday
4. Delete a birthday
5. Quit the program

Enter your choice: 1 enter


Enter a name: Kathryn enter
5/7/1989

Friends and Their Birthdays


---------------------------
1. Look up a birthday
2. Add a new birthday
3. Change a birthday
4. Delete a birthday
5. Quit the program

Enter your choice: 3 enter


Enter a name: Kathryn enter
Enter the new birthday: 5/7/1988 enter

Friends and Their Birthdays


---------------------------
1. Look up a birthday
2. Add a new birthday
3. Change a birthday
4. Delete a birthday
5. Quit the program

Enter your choice: 1 enter


Enter a name: Kathryn enter
5/7/1988

Friends and Their Birthdays


---------------------------
1. Look up a birthday
2. Add a new birthday
3. Change a birthday
4. Delete a birthday
5. Quit the program
Enter your choice: 4 enter
Enter a name: Cameron enter
Training imparted by: Michael Devine. #8884009669
PROGRAMMING WITH PYTHON 3.6. – DICTIONARIES - 1

Friends and Their Birthdays


---------------------------
1. Look up a birthday
2. Add a new birthday
3. Change a birthday
4. Delete a birthday
5. Quit the program

Enter your choice: 1 enter


Enter a name: Cameron enter
Not found.

Friends and Their Birthdays


---------------------------
1. Look up a birthday
2. Add a new birthday
3. Change a birthday
4. Delete a birthday
5. Quit the program

Enter your choice: 5 enter

Training imparted by: Michael Devine. #8884009669


PROGRAMMING WITH PYTHON 3.6. – DICTIONARIES - 1

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:

One point A, E, I, L, N, O, R, S, T and U


Two points D and G
Three points B, C, M and P
Four points F, H, V, W and Y
Five points K
Eight points J and X
Ten points Q and Z

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

You might also like