0

I am currently preparing for a python exam and one topic we are expected to understand is having to flip a dictionary in which values become the keys and the keys become values. I am confused as to what this asking and if someone could provide me with a basic example to see what it looks like I would greatly appreciate it.

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
shibaking
  • 61
  • 1
  • 6

1 Answers1

4

Simply write a dict comprehension expression and make it's key as value and values as key. For example:

>>> my_dict = {1: 2, 3: 4, 5: 6}
>>> {value: key for key, value in my_dict.items()}
{2: 1, 4: 3, 6: 5}

Note: Since, dict contains unique keys. In case you have same element as value for multiple keys in your original dict, you will loose related entries. For example:

# Same values     v           v
>>> my_dict = {1: 2, 3: 4, 5: 2}
>>> {value: key for key, value in my_dict.items()}
{2: 5, 4: 3}
#^ Only one entry of `2` as key 
Markus Meskanen
  • 19,939
  • 18
  • 80
  • 119
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126