Swapping Content of Two Dictionaries.

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Wed Mar 17 23:38:21 CET 2010


On Wed, 17 Mar 2010 13:34:51 +0100, Peter Otten wrote:

> Hatem Oraby wrote:
> 
>> Hello, I want to swap the content of two dictionaries, the obvious way
>> to do it is:
>> a = {1:"I'am A"}
>> b = {2:"I'm B"}
>> temp = a
>> a = b
>> b = temp
> 
> That can be simplified to
> 
> a, b = b, a
> 
> and is almost certainly the right approach.


Unfortunately, it may not, because it doesn't swap the content of two 
dictionaries (as asked for), but instead swaps the dictionaries bound to 
two names, which is a very different kettle of fish indeed.

It may be that the OP's description of his problem is inaccurate, in 
which case a simple re-binding is the easiest way, but if the subject 
line is accurate, then he needs your suggested solution using a temporary 
dict, clear and update. Wrap it in a function, and you have a one-liner 
swap operation :)



-- 
Steven



More information about the Python-list mailing list