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.
Asked
Active
Viewed 1,539 times
0
-
1What code have *you* tried thus far? – blacksite Dec 04 '16 at 23:24
-
I mean, this is one statement, there aren't that many things one can try. You either know how to do it or not... Better question would be if he's done any research on the issue yet. @not_a_robot – Markus Meskanen Dec 04 '16 at 23:28
-
That's kind of implied... I just didn't want to give it away :) – blacksite Dec 04 '16 at 23:32
1 Answers
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
-
Why not add an example too, I've never heard of anyone complaining of too many examples! :) – Markus Meskanen Dec 04 '16 at 23:51