How to exchange values between specific keys in a dictionary?

梦想与她 提交于 2021-02-05 08:24:34

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/14830555/how-to-exchange-values-between-specific-keys-in-a-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!