Invert-a-dict (2) T40928


Statement
 

pdf   zip

thehtml

A dictionary where values are lists can be inverted obtaining another dictionary where the keys are the elements in value lists of the original dictionary, and values are lists of the original keys.

  1. Program a function inverse(d) that given an dictionary d with string keys and lists of strings as values, returns its inverse.

    For instance, if the original dictionary d is:

    { 'John' : ['AP1', 'CAOS', 'POC', 'MB'],
      'Mary' :  ['CAOS', 'MB', 'ALG'],
      'Sheila' : ['CAL']
      'Peter' :  ['AP1', 'ALG', 'POC', 'CB', 'MB'] 
    }
    

    the function will return

    { 'AP1': ['John', 'Peter'],
      'CAOS': ['John', 'Mary'],
      'POC': ['John', 'Peter'],
      'MB': ['John', 'Mary', 'Peter'],
      'ALG': ['Mary', 'Peter'],
      'CAL': ['Sheila']
      'CB': ['Peter']
    }
    
  2. Write a main program that reads a dictionary, uses the inverse(d) function to obtain the inverted dictionary, and prints the result.

Input

The input is a dictionary in the following format:

  • Each line contains several strings separated by whitespaces, describing a single dictionary entry.
  • The first string in the line is the key, and the remaining strings are the list of values for that key.
  • Each line has at least two string (the key plus at least one element for the list value).
  • All strings in the list value for a key are different.

Output

The output is the inverted dictionary. Keys are printed in lexicographical order, and so are their corresponding lists of values. Follow the format of the examples.

Public test cases
  • Input

    John AP1 CAOS POC MB
    Mary CAOS MB ALG
    Sheila CAL
    Peter AP1 ALG POC CB MB

    Output

    ALG: Mary Peter
    AP1: John Peter
    CAL: Sheila
    CAOS: John Mary
    CB: Peter
    MB: John Mary Peter
    POC: John Peter
    
  • Input

    carrots 3 4 5 
    potatoes 1 2 3 4
    spinach 4 5 6 7 8
    oranges 5 6
    apples 2

    Output

    1: potatoes
    2: apples potatoes
    3: carrots potatoes
    4: carrots potatoes spinach
    5: carrots oranges spinach
    6: oranges spinach
    7: spinach
    8: spinach
    
  • Input

    john twitter insta github linkedin
    peter insta facebook
    mary twitter github facebook
    sheila insta github

    Output

    facebook: mary peter
    github: john mary sheila
    insta: john peter sheila
    linkedin: john
    twitter: john mary
    
  • Information
    Author
    Lluís Padró
    Language
    English
    Official solutions
    Python
    User solutions
    Python