user1879926
user1879926

Reputation: 1323

Switching Two Values in Dictionary, Keeping Keys Constant

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

Answers (2)

juanchopanza
juanchopanza

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

Martijn Pieters
Martijn Pieters

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

Related Questions