Introduction to Python
davidbpython.com
In-Class Exercise Solutions, Session 5
DICTIONARIES: INITIALIZING, ADDING/READING PAIRS, CHECKING FOR MEMBERSHIP |
|
Ex. 5.1 | Perform basic operations on a dict. |
Suggested Solution:
# initialize the dict
thisd = {'U.S.': 'Columbia', 'Great Britain': 'Britannia', 'France': 'Marianne'} # dict
# print the dict and print its type
print(thisd)
print(type(thisd))
# add a key/value pair (use dict subscript with key and value)
thisd['Italy'] = 'Italia turrita' # (dict above with {'f': 99} added)
print(thisd)
# add a duplicate key with a new value
thisd['U.S.'] = 'Uncle Sam' # dict, {'U.S.': 'Uncle Sam' ...}
print(thisd)
# access and print a single value in the dict (use dict subscript with key)
val = thisd['France']
print(val)
# check to see if a key exists in the dict (use 'if key in dict').
# If so, print 'found', else print 'not found'. Test with both
# existing key and non-existent key.
if 'Italy' in thisd: # bool, True
print('found')
else:
print('not found')
|
|
Ex. 5.2 | Add key/value pairs, then query dict. |
Initialize an empty dictionary. Then in 2 statements, add 2 key/value pairs using the variables below. Then use a subscript to print the value -48 using the key Fargo. |
|
city_lotemps = {'New York': -15, 'Fargo': -48, 'Honolulu': 52}
city = 'Death Valley'
temp = 20
city_lotemps[city] = temp
print(city_lotemps)
print(city_lotemps['Fargo'])
|
|
Ex. 5.3 | Demo: generate KeyError exception. |
Run the below program, entering a key in the dict. Then enter a key that is not in the dict. Note the exception type and message. |
|
myd = {'a': 1, 'b': 2, 'c': 3} # dict
ukey = input('please enter a key: ') # str, 'd' (sample value)
print(myd[ukey]) # KeyError: 'd'
|
|
If the key is not in the dict, Python will raise a KeyError exception. The message is not at all descriptive - Python simply notes the key that was requested. |
|
Ex. 5.4 | Test for presence of a key. |
Take user input for a key. If the key exists in the dict, print the value for that key, but if the key is not found in the dict, print "not found". |
|
dis = { 'Mickey': 'Mouse',
'Donald': 'Duck',
'Goofy' : 'Dog(?)' }
char = input('please enter the name of a character: ')
if char in dis:
print(dis[char])
else:
print(f'"{char}"" not found')
|
|
LAB 1 |
|
Ex. 5.5 | Add a key. |
Take two inputs from the user and add them as key/value pair to the below dict. Print the dict to see that it has been added. |
|
Suggested Solution:
cocap = {'Apple': 1.98, 'Microsoft': 1.55, 'Amazon': 1.57 } # dict
company = input('please enter a company name: ') # str, 'Salesforce'
cap = input('please enter a market cap in Tn: ') # str, .219
cocap[company] = float(cap) # adds {'Salesforce': 0.219} to above
print(cocap)
|
|
Ex. 5.6 | Access a value based on a key. |
Take input from the user for a chemical compound, and print the boiling point associated with that key in the dict. |
|
Suggested Solution:
bps = { 'water': 212,
'methanol': 148.5,
'wax': 698 }
compound = input('please enter a compound: ') # str, 'water' (sample value)
print(bps[compound]) # 212
|
|
Ex. 5.7 | Test for presence of a key. |
Again take user input for a key. If the key exists in the dict, print the value for that key, but if the key is not found in the dict, print "not found". |
|
Suggested Solution:
deage = { 'Biden': 77,
'Harris': 55,
'Sanders': 79 }
can = input('please enter the name of a candidate: ') # str, 'Harris' (sample value)
if can in deage: # bool, True
print(deage[can]) # 55
else:
print('not found')
|
|
DICTIONARIES: LOOPING THROUGH |
|
Ex. 5.8 | Loop through and print each dict key, then modify the loop to print the key as well as the value. |
Suggested Solution:
pdist = { 'Earth': 149.6,
'Mars': 227.9,
'Venus': 108.2,
'Mercury': 57.9 } # dict
# loop through the dict keys
for key in pdist: # str, 'Earth' (initial value)
# print each key and the value for that key
print(key, pdist[key]) # Earth, 149.6
|
|
DICTIONARIES: SORTING KEYS |
|
Ex. 5.9 | Sort dict keys. |
Sort the keys in this dict. Print the list of sorted keys. Then loop through the sorted list and print each key as well as the value associated with that key from the dict. |
|
Suggested Solution:
uscitypop = { 'Houston': 2.3,
'Los Angeles': 4.0,
'Chicago': 2.7,
'New York': 8.4 } # dict
# sort and print the dict keys
skeys = sorted(uscitypop) # list, ['Chicago', 'Houston' ... ]
# loop through the sorted keys
for key in skeys: # str, 'Chicago' (initial value)
# print each sorted key and the value for that key in the dict
print(key, uscitypop[key]) # Chicago, 2.7
|
|
Ex. 5.10 | Sort dict keys by value. |
Sort the keys in this dict by value, low to high, then loop through and print each key and associated value. Next, sort the keys by value by adding additional arguments to sorted(), key=uscitypop.get and reverse=True to sort the keys by value, high to low. Print the sorted keys and see that they are in the order ['New York', 'Los Angeles', 'Chicago', 'Houston']. Loop through these sorted keys and print sorted keys and values. |
|
Suggested Solution:
uscitypop = { 'Houston': 2.3,
'Los Angeles': 4.0,
'Chicago': 2.7,
'New York': 8.4 } # dict
# sort dict keys by value; print the keys
skeys = sorted(uscitypop, key=uscitypop.get, reverse=True)
# list, ['New York', 'Los Angeles', 'Chicago', 'Houston']
# loop through the sorted keys
for key in skeys: # str, 'New York' (initial value)
# print each sorted key and the value for that key in the dict
print(key, uscitypop[key]) # New York 8.4
|
|
LAB 2 |
|
Ex. 5.11 | Loop through and print keys and values of a dict. |
Loop through the below dict and print each key and associated value. You can use the comma between values when printing, e.g. print(this, that). |
|
Suggested Solution:
planet_colors = { 'Mercury': 'green',
'Venus': 'white',
'Earth': 'blue',
'Mars': 'red',
'Jupiter': 'orange' } # dict
for key in planet_colors: # str, 'Mercury' (initial value)
print(key, planet_colors[key]) # Mercury, green
|
|
Ex. 5.12 | Sort a dict's keys and print. |
Sort the dict's keys, loop through the sorted keys and print each key and associated value from the dict. You can use the comma between values when printing, e.g. print(this, that). |
|
Suggested Solution:
towers = {
'Shanghai Tower': 128,
'Burj Khalifa': 163,
'Lotte World Tower': 123,
'One World Trade Center': 104,
'Ping An Finance Center': 115,
'Abraj Al-Bait Clock Tower': 120,
} # dict
skeys = sorted(towers) # list, ['Abraj Al-Bait Clock Tower', 'Burj Khalifa' ...]
for key in skeys: # str, 'Abraj Al-Bait Clock Tower'
print(key, towers[key]) # Abraj... 120
|
|
Ex. 5.13 | Sort a dict's keys by value and print. |
Sort the dict's keys by value in reverse order, loop through the sorted keys and print each key and associated value from the dict. |
|
Suggested Solution:
towers = {
'Shanghai Tower': 128,
'Burj Khalifa': 163,
'Lotte World Tower': 123,
'One World Trade Center': 104,
'Ping An Finance Center': 115,
'Abraj Al-Bait Clock Tower': 120, # dict
}
skeys = sorted(towers, key=towers.get, reverse=True)
# list, ['Burj Khalifa', 'Shanghai Tower', 'Lotte World Tower' ...]
for key in skeys: # str, 'Burj Khalifa'
print(key, towers[key]) # Burj Khalifa 163
|
|
DICTIONARIES: BUILDING FROM FILE |
|
Ex. 5.14 | Assign a CSV line to separate variables. |
Split the below CSV line into items, then assign the items to variables fname, lname and job. Print the variables fname and lname. |
|
line = 'Joe,Wilson,Mechanic' # str, 'Joe,Wilson,Mechanic'
fname, lname, job = line.split(',') # 'Joe', 'Wilson', 'Mechanic'
print(fname)
print(lname)
|
|
Ex. 5.15 | Build a "lookup" dict from row values in a CSV file. |
Looping through revenue.csv, build a dict with the company name as string key and the revenue number as float value. |
|
Suggested Solution:
corev = {} # dict, {}
fh = open('../revenue.csv') # 'file' object
for line in fh: # str, "Haddad's,PA,239.50"
company, state, rev = line.split(',') # "Haddad's", 'PA' '239.50'
corev[company] = state # adding {"Haddad's": 'PA'}
fh.close()
print(corev)
|
|
Ex. 5.16 | Build a "counting" dict from a file. |
Again looping through revenue.csv, build a dict that counts how many states are in the 2nd column. |
|
Suggested Solution:
corevcount = {} # dict, {}
fh = open('../revenue.csv') # 'file' object
for line in fh: # str, "Haddad's,PA,239.50"
company, state, rev = line.split(',') # "Haddad's", 'PA', '239.50'
if state not in corevcount: # bool, True (initial value)
corevcount[state] = 1 # {'PA': 1}
else:
corevcount[state] = corevcount[state] + 1
fh.close()
print(corevcount)
|
|
LAB 3 |
|
Ex. 5.17 | Assign a list to separate variables. |
Use multi-target assignment to "unpack" the items in the list to three separate variables called company, business and state. Print company (should be Acme) and state (should be California). |
|
Suggested Solution:
items = ['Acme', 'Manufacturing', 'California'] # list
company, business, state = items # 'Acme', 'Manufacturin', 'California'
print(company)
print(state)
|
|
Ex. 5.18 | Split a string's fields to separate variables. |
Taking the previous one step further, split the below string into 3 items and unpack them into three separate variables called company, business and state. Print company (should be Acme) and state (should be California). |
|
Suggested Solution:
line = 'Acme,Manufacturing,California' # str, 'Acme,Manfuacturing...'
company, business, state = line.split(',') # 'Acme', 'Manufacturing', 'California'
print(company)
print(state)
|
|
Ex. 5.19 | Build a dict from file. |
Looping through student_db_names.txt below, build up a dict of student ids to last name. Print the dict. |
|
Suggested Solution:
fname = '../student_db_names.txt' # str, '../student_db_names.txt'
fh = open(fname) # 'file' object
next(fh) # str, 'id:fname:lname:address:city:state:zip\n'
sn = {} # dict, {}
for row in fh: # str, 'jk43:John:Kane:23 Marfield Lane:Plainview:NY:10024\n'
stuid, fname, lname, address, city, state, stuzip = row.split(':')#
sn[stuid] = lname # adds {'jk43': 'Kane'} to dict
print(sn)
|
|
Ex. 5.20 | Build a counting dict. |
Looping through revenue.csv below, build up a dict with state keys and a count of each state as values. Print the dict. |
|
Suggested Solution:
fname = '../revenue.csv' # str, '../revenue.csv'
fh = open(fname) # 'file' object
statecount = {} # dict, {}
for row in fh: # str, "Haddad's,PA,239.50
" (sample value)
name, state, amount = row.split(',') # "Haddads", 'PA', '239.50'
if state not in statecount: # bool, True
statecount[state] = 1 # {'PA': 1}
else:
statecount[state] = statecount[state] + 1 #
print(statecount)
|
|
DICTIONARIES: len(), .get(), KEYS, VALUES, ITEMS |
|
Ex. 5.21 | Get the length of a dict. Use len(). Print the result. |
thisd = {'a': 1, 'b': 2, 'c': 3} # dict
dlen = len(thisd) # int, 3
print(dlen) # 3
|
|
Ex. 5.22 | Use .get() to get a value for a key. Input a key that exists in the dict and use .get() with the key to get the value. Then input a key that does not exist and note the return value. |
thisd = {'a': 1, 'b': 2, 'c': 3} # dict
ukey = input('please enter a key: ') # str, 'b' (sample value)
uval = thisd.get(ukey) # int, 2
print(uval)
|
|
With an existing key (like 'b'), .get() returns the value (like 2). With a key that does not exist, the value should be None (Python's "null" value, or "the value that means no value".) |
|
Ex. 5.23 | Show keys, values and items in a dict. |
Use the so-named dict methods to retrieve keys, values and items from the dict. |
|
Suggested Solution:
tvshows = { 'The Twilight Zone': 1959,
'Star Trek': 1966,
'I Love Lucy': 1951,
'Lost': 2004 } # dict
# print list of keys (use list() with dict, or list() with .keys())
print(list(tvshows)) # ['The Twilight Zone', 'Star Trek' ...]
print(list(tvshows.keys())) # ['The Twilight Zone', 'Star Trek' ...]
# print list of values (use list() with .values())
print(list(tvshows.values())) # [1959, 1966, 1951, 2004]
# print list of items (use list with .items())
print(list(tvshows.items())) # [('The Twilight Zone', 1959) ... ]
|
|
TRAPPING EXCEPTIONS: TRY/EXCEPT |
|
Ex. 5.24 | Trap a "bad dict key" error. If the user's key can't be found in the dict, an error occurs -- test this by inputting a key of 'XXX'. Once you have observed the exception and exception type, use a 'try/except' statement to trap the exception and instead print 'key does not exist'. Make sure to put your 'try' block around just one line of code. |
Suggested Solution:
z = {'a': 1, 'b': 2, 'c': 3} # dict
ukey = input('please enter a key: ') # str, 'x' (sample value)
try:
print(z[ukey]) # z['x']: raises KeyError
except KeyError:
print('key does not exist')
|
|
Ex. 5.25 | Trap a "bad list index" error. If the user's index can't be found in the list, an error occurs -- test this by inputting an index of 9. Once you have observed the exception and exception type, use a 'try/except' statement to trap the exception and instead print 'no value at that index'. Make sure to put your 'try' block around just one line of code. |
Suggested Solution:
x = ['a', 'b', 'c', 'd'] # list, ['a', 'b' ... ]
uidx = int(input('please enter an index: ')) # str, '99' (sample value)
try:
print(x[uidx]) # x[99]: raises IndexError
except IndexError:
print('no value at that index')
|
|
Ex. 5.26 | Trap a "bad int value" error. Add another except: block to the one below that will trap the exception that occurs if the user doesn't type a number. If this exception is trapped, print 'please enter a number'. |
Suggested Solution:
x = ['a', 'b', 'c', 'd'] # list, ['a', 'b' ...]
try:
uidx = int(input('please enter an index: ')) # int, 'nine' (sample value)
print(x[uidx]) # x['nine'] raises ValueError
except IndexError: #
print('no value at that index')
except ValueError:
print('please enter a number') # prints
|
|