Invert-a-dict X82126


Statement
 

pdf   zip   main.py

html

A dictionary is said to be invertible if all keys are associated to a different value (and thus, each value happens only once).

Program a function inverse(d) that given an invertible dictionary d with string keys and int values, returns its inverse. That is, a dictionary where each int value in the original dictionary is now a key, and its string key in the original dictionary is now its associated value.

For instance, if the original dictionary d is:

{ 'hello' : 3,
  'bye' : 5,
  'someone' : 1 }

the function will return

{ 3: 'hello',
  5: 'bye',
  1: 'someone' }

The function does not have to deal with non-invertible dictionaries. The received dictionary will always be invertible.

Observation

Only the function will be evaluated. If your submission includes a main program (e.g. with testmod), it must be either commented out or inside a condition if __name__ == ’__main__’

Sample session
>>> inverse({'hello': 3, 'bye': 5, 'someone': 1})
{3: 'hello', 5: 'bye', 1: 'someone'}
>>> inverse({'carrots': 3, 'potatoes': 1, 'spinach': 4, 'oranges': 5, 'apples': 2})
{3: 'carrots', 1: 'potatoes', 4: 'spinach', 5: 'oranges', 2: 'apples'}
>>> inverse({'age': 23, 'height': 181, 'kg': 77, 'head': 1})
{23: 'age', 181: 'height', 77: 'kg', 1: 'head'}
Information
Author
ProAl1
Language
English
Official solutions
Python
User solutions
Python