Homework 3 - 3.4 Dictionaries, where is my error? I'm trying to solve the problem with a dictionary containing names and ages and I don't see why my code is wrong. def people(x): new = combine_lists(NAMES, AGES) #the function creates a dictionary for item in new: if new[item] == x: return item print people(18) For each name I check whether the value (=age) is say 18 or any other age and actually it should return all names with this age, but I only get one key even if there are more people with this age. What am I doing wrong? Thanks
You're returning from people instead of accumulating, in say a list, your matches.
I solved the problem using the function below. The program returns 'True' to all test cases, but it returns 'False' to the final test case, when it should return an empty list ! I'm not sure where i'm going wrong!? def people(n): """ takes a value and returns dictionary keys of that value""" di = (combine_lists(names,ages)) li=[] for na,a in di.iteritems(): if a == n: li.append(na) for look in li: return li print 'd' in people(18) and 'c' in people(18) print 'e' in people(19) and 'h' in people(19) and\ 'i'in people(19) and 'j' in people(19) and 'l' in people(19) print 'a' in people(20) and 'f' in people(20) and 'g'in people(20) print people(21) == ['b'] print people(22) == ['k'] print people(23) == []
Join our real-time social learning platform and learn together with your friends!