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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With