-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'} 
2
  • See this answer on how to flip keys and values in a dictionary. Commented Oct 31, 2019 at 20:47
  • @foureyes9408 no, don't; see this answer 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 Commented Oct 31, 2019 at 21:06

3 Answers 3

1
reverse_dict = {value: key for key, value in dict.items()} 
Sign up to request clarification or add additional context in comments.

Comments

0

Map reversed to the dicts items:

def reverse(dct): return dict(map(reversed, dct.items())) 

Comments

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) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.