Reputation: 1323
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?
Upvotes: 1
Views: 396
Reputation: 227418
The same way you would swap any other values:
my_dict[key0], my_dict[key1] = my_dict[key1], my_dict[key0]
Upvotes: 3
Reputation: 1122302
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).
Upvotes: 3