replace dict contents

Christos TZOTZIOY Georgiou tzot at sil-tec.gr
Wed Jul 28 12:13:06 CEST 2004


On Tue, 27 Jul 2004 22:10:42 +0100, rumours say that Robin Becker
<robin at SPAMREMOVEjessikat.fsnet.co.uk> might have written:

>Peter Otten wrote:
>> Tim Jarman wrote:
>> 
>> 
>>>On 27 Jul 2004, at 08:56, Robin Becker wrote:

[Robin]
>>>>Is there a simple way to replace the contents of a dictionary entirely
>>>>with those of another.
>>>>
>>>>for lists we can do
>>>>
>>>>L1[:] = L2

[Tim J]
>>>How about:
>>>
>>> >>> d1 = { "spam" : "eggs" }
>>> >>> d2 = { "gumby" : "my brain hurts!"}
>>> >>> d1 is d2
>>>False
>>> >>> d1 = dict(d2)

[Peter]
>> This rebinds the name d1 to a copy of d2 and will not affect other
>> references to the original d1.

[Robin]
>Peter has the essence of the problem. Attempts to change sys.modules 
>have strange effects eg try this simple script
>
[snip]
>
>The actual replace part of  L1[:]=L2 happens in a single opcode and is 
>therefore atomic. The same cannot be said of the .clear, .update sequence.

A compromise, then, which might be good enough: first update, then
remove all missing keys in two operations. ie

>>> d1.update(d2)
>>> list(itertools.ifilter(None, itertools.imap(d1.__delitem__, set(d1)-set(d2))))

An 'import itertools' is implied.  As soon as the keys to be deleted are
calculated, the rest of the second operation is atomic (I believe!).
-- 
TZOTZIOY, I speak England very best,
"Tssss!" --Brad Pitt as Achilles in unprecedented Ancient Greek



More information about the Python-list mailing list