pemistahl
pemistahl

Reputation: 9584

How to exchange values between specific keys in a dictionary?

Let's say you have a dictionary like this:

d = {
    'A': 'content_for_A',
    'B': 'content_for_B'
}

What is the most efficient way to swap the values between the two entries? So the result should be like this:

d = {
    'A': 'content_for_B',
    'B': 'content_for_A'
}

Of course, you can create a new dictionary d2 and do d2['A'] = d['B']; d2['B'] = d['A'] but is this the recommended way or is there an efficient way without the need to create a new dictionary?

Upvotes: 4

Views: 4890

Answers (2)

Cati Lucian
Cati Lucian

Reputation: 1

{'1': '1', '2': None, '3': '3'}

Expected

{'1': '3', '2': None, '3': '1'}

Solution

dict([(key, num) for (key, _), num in zip(your_dict.items(), reversed(list(your_dict.values())))])

Upvotes: 0

Volatility
Volatility

Reputation: 32300

d['A'], d['B'] = d['B'], d['A']

Tuple unpacking is a great tool in Python to swap the values of two objects without the need of creating an intermediary variable.

Upvotes: 19

Related Questions