-3

I need to write a function that's these reverses the input.

Write a function reverse(dct) that takes as input a dict and returns a new dict where the keys and values have been flipped. You can assume the input dict has only string values.

What would be the code for this?

.>>> reverse({"boy": "ragazzo", "girl": "ragazza", "baby": "bambino"})

{'ragazzo': 'boy', 'ragazza': 'girl', 'bambino': 'baby'}


.>>> reverse({"boy": "niño", "girl": "niña", "baby": "bebe"})

{'niño': 'boy', 'niña': 'girl', 'bebe': 'baby'}

.>>> reverse({"boy": "garcon", "girl": "fille", "baby": "bébé"})

{'garcon': 'boy', 'fille': 'girl', 'bébé': 'baby'}
Klaus D.
  • 13,874
  • 5
  • 41
  • 48
  • See [this answer](https://stackoverflow.com/a/1031878/12095613) on how to flip keys and values in a dictionary. – foureyes9408 Oct 31 '19 at 20:47
  • @foureyes9408 no, don't; see [this answer](https://stackoverflow.com/a/1087957/4799172) which is more idiomatic. There's nothing wrong with the top answer, but I don't see why they called `dict()` rather than use a dictionary comprehension that came with Python 3 – roganjosh Oct 31 '19 at 21:06

3 Answers3

1
reverse_dict = {value: key for key, value in dict.items()}
Max Voisard
  • 1,685
  • 1
  • 8
  • 18
0

Map reversed to the dicts items:

def reverse(dct):
    return dict(map(reversed, dct.items()))
Jab
  • 26,853
  • 21
  • 75
  • 114
0

It gonna be like: (i use python 3.7)

def reverse(my_map):
    inv_map = {v: k for k, v in my_map.items()}
    return(inv_map)
alexandrov
  • 363
  • 3
  • 11