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 391 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
- 1,048,767
- 296
- 4,058
- 3,343
3
The same way you would swap any other values:
my_dict[key0], my_dict[key1] = my_dict[key1], my_dict[key0]
juanchopanza
- 223,364
- 34
- 402
- 480