Swapping Content of Two Dictionaries.
Peter Otten
__peter__ at web.de
Wed Mar 17 08:34:51 EDT 2010
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
More information about the Python-list
mailing list