What would be the most efficient way to switch say two values in a dictionary, so that two keys would be mapping to two different values?
Asked
Active
Viewed 386 times
2 Answers
3
Use tuple assignment:
d['bar'], d['foo'] = d['foo'], d['bar']
This simply swaps the values. The Python compiler optimizes for such cases, and this doesn't require any frame stack pushes (provided d doesn't implement __getitem__ and / or __setitem__ hooks in Python code).
Community
- 1
- 1
Martijn Pieters
- 963,270
- 265
- 3,804
- 3,187
3
The same way you would swap any other values:
my_dict[key0], my_dict[key1] = my_dict[key1], my_dict[key0]
juanchopanza
- 216,937
- 30
- 383
- 461