> 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
Looks like the interface of your module is broken. It shouldn't export the
two dicts.
> 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.
Please explain what you use the dicts for and how they are supposed to be
used by your own code and by external code. That will allow us to give an
advice on how to design your module better.
Stefan
> 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