如何在字典中的特定键之间交换值?(How to exchange values between specific keys in a dictionary?)
假设你有这样一本字典:
d = { 'A': 'content_for_A', 'B': 'content_for_B' }在两个条目之间交换值的最有效方法是什么? 所以结果应该是这样的:
d = { 'A': 'content_for_B', 'B': 'content_for_A' }当然,你可以创建一个新的字典d2并做d2['A'] = d['B']; d2['B'] = d['A'] d2['A'] = d['B']; d2['B'] = d['A']但这是推荐的方式还是有效的方式,而不需要创建一个新的字典?
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']在Python中,Tuple解包是一个很好的工具,可以在不需要创建中间变量的情况下交换两个对象的值。
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.
更多推荐
发布评论