-1

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
  • 43,657
  • 11
  • 92
  • 117
shibaking
  • 51
  • 6

1 Answers1

3

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
  • 17,674
  • 15
  • 70
  • 114
Moinuddin Quadri
  • 43,657
  • 11
  • 92
  • 117