Skip to content
Exercise · Comprehensions · lesson 8 of 8

Exercise: invert a dict

Write a function invert(d). It returns a new dict in which the keys and values of the dict d have swapped places: each value of d becomes a key, and its key becomes the value.

  • invert({"a": 1, "b": 2}) → {1: 'a', 2: 'b'}
  • invert({"x": "y"}) → {'y': 'x'}
  • invert({}) → {}

Constraints: the keys and values of d are numbers or strings; all the values are different; an empty dict gives an empty dict; the function does not change d itself.

Do not add extra imports unless the task says so explicitly.

invert.py — python
python · 3 lines
Ctrl+Enter run · Esc leave editor

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way