如何在字典中的特定键之间交换值?(How to exchange values between specific keys in a dictionary?)

编程入门 行业动态 更新时间:2024-10-21 15:54:18
如何在字典中的特定键之间交换值?(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.

更多推荐

本文发布于:2023-04-29 04:15:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1334539.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字典   如何在   exchange   values   keys

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!