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

查看:41
本文介绍了如何在字典中的特定键之间交换值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有一本这样的字典:

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'
}

当然,您可以创建一个新字典 d2 并执行 d2 ['A'] = d ['B'];d2 ['B'] = d ['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 unpacking is a great tool in Python to swap the values of two objects without the need of creating an intermediary variable.

这篇关于如何在字典中的特定键之间交换值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆