[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

Re: Swapping Content of Two Dictionaries.

Peter Otten

3/17/2010 12:35:00 PM

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.

> tempKeys = a.keys()
> diffKeys = a.keys() - b.keys() #I do it using set()s
>
> #item = a
> temp = {}
> for key in a.keys():
> item[key] = a[key]
>
> for key in diffKeys:
> del a[key] #delete stuff that exist in a but not b.
>
> for key in b.keys():
> a[key] = b[key]
>
> b = temp
>
> This works great as the content referenced by the dictionary is changed
> rather than changing the reference of dictionary itself so it's reflected
> by any "scope" that references the dictionary.
>
> My problem is that i need to do this operation a LOT, simply I got a
> problem that my program go through a very long loop and inside this loop
> this operation is needed to be done twice and the dictionary size ain't
> very small.

You could try

>>> a = {"a": 1, "b": 2}
>>> b = {"b": 3, "c": 4}
>>> t = a.copy()
>>> a.clear()
>>> a.update(b)
>>> b.clear()
>>> b.update(t)
>>> a
{'c': 4, 'b': 3}
>>> b
{'a': 1, 'b': 2}

> If anyone has a suggestion one how to do it faster then please feel free
> and welcome to contribute.

> Anyway, I decided to go and implement it in C to gain performance, And

Premature optimization? If you explain what you are trying to achieve
someone might come up with a way to do it without swapping dict contents.

Peter


1 Answer

Steven D'Aprano

3/17/2010 10:38:00 PM

0

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