# This code demonstrates: # (1) iterating through a dictionary to find all the keys associated with # a value. # (2) the more general case: building an "inverted" dictionary. def main(): # The owner of various phone numbers. phone = {'555-7632': 'Paul', '555-9832': 'Andrew',\ '555-6677': 'Jen', '555-9823': 'Michael',\ '555-6342' : 'Wael', '555-7343' : 'Paul',\ '555-2222' : 'Michael'} # (1) Make a list of Paul's phone numbers. # Make a list of all the keys # If the key's value is Paul, take that key out # Append all these keys together. pauls_phone_numbers = [] for key in phone: if phone[key] == "Paul": # append that key to the list pauls_phone_numbers.append(key) print(pauls_phone_numbers) # (2) Make a new dictionary that is "inverted". # It will have names as keys, and the value for a name will be # the list of that person's phone numbers. inverted_dictionary = {} for (number, name) in phone.items(): # In the inverted dictionary, we want to use name # as the key if name in inverted_dictionary: # The name is already in the inverted dictionary. # So it already has a value (a list of numbers). # Append to that. inverted_dictionary[name].append(number) else: # Name is not in the inverted dictionary yet. Add it, with its # number. inverted_dictionary[name] = [number] print(inverted_dictionary) main()