#------------------------------ # PROBLEM 4 #------------------------------ # # Given two lists: # # names = ['Alice', 'Bob', 'Cathy', 'Dan', 'Ed', 'Frank', 'Gary', 'Helen', 'Irene', 'Jack', 'Kelly', 'Larry'] # ages = [20, 21, 18, 18, 19, 20, 20, 19, 19, 19, 22, 19] # # These lists match up, so Alice's age is 20, Bob's age is 21, and so on. # Write a function combine_lists that combines these lists into a dictionary # Hint 1: what should the keys of this dictionary? # Hint 2: what should be the values of this dictionary? # Write a function 'people(age)' that takes in an age and returns the names of all the people who are that age. # # TEST PROGRAM (QA): # Test your program's functions by running the following Python code: # # print 'Dan' in people(18) and 'Cathy' in people(18) # print 'Ed' in people(19) and 'Helen' in people(19) and 'Irene' in people(19) and 'Jack' in people(19) and 'Larry' in people(19) # print 'Alice' in people(20) and 'Frank' in people(20) and 'Gary' in people(20) # print people(21) == ['Bob'] # print people(21) == ['Bob', 'Dan', 'Kelly'] # print people(23) == [] # SOLUTION: #---------------------------------------------- def combine_lists(keys, values): d = dict() i = 0 for key in keys: d[key] = values[i] i += 1 return d def people(age): "List all people with the given age" names = list() for name in d.keys(): if d[name] == age: names.append(name) return names # SECOND SOLUTION: Here is a more advanced solution! # Look up what the zip command does? and how dict operates here? def combine_lists_2(keys, values): return dict(zip(keys, values)) # EXAMPLE USAGE #---------------------------------------------- if __name__ == "__main__": names = ['Alice', 'Bob', 'Cathy', 'Dan', 'Ed', 'Frank', 'Gary', 'Helen', 'Irene', 'Jack', 'Kelly', 'Larry'] ages = [20, 21, 18, 18, 19, 20, 20, 19, 19, 19, 22, 19] d = combine_lists(names, ages) print 'Dan' in people(18) and 'Cathy' in people(18) print 'Ed' in people(19) and 'Helen' in people(19) and 'Irene' in people(19) and 'Jack' in people(19) and 'Larry' in people(19) print 'Alice' in people(20) and 'Frank' in people(20) and 'Gary' in people(20) print people(21) == ['Bob', 'Dan', 'Kelly'] print people(22) == ['Kelly'] print people(23) == [] print people(20) == ['Gary', 'Larry', 'Frank']