Patches item #1391204, was opened at 2005-12-27 08:00
Message generated for change (Settings changed) made by gvanrossum
You can respond by visiting:
https://sourceforge.net/tracker/?func=detail&atid=305470&aid=1391204&group_id=5470
Please note that this message will contain a full copy of the comment thread,
including the initial issue submission, for this request,
not just the latest update.
Category: Core (C code)
Group: Python 2.5
>Status: Closed
>Resolution: Rejected
Priority: 5
Submitted By: Nicolas Lehuen (nlehuen)
Assigned to: Guido van Rossum (gvanrossum)
Summary: dict.merge
Initial Comment:
If you want to update a dictionary with another one,
you can simply use update :
a = dict(a=1,c=3)
b = dict(a=0,b=2)
a.update(b)
assert a == dict(a=0,b=2,c=3)
However, sometimes you want to merge the second dict
into the first, all while keeping the values that are
already defined in the first. This is useful if you
want to insert default values in the dictionary without
overriding what is already defined.
Currently this can be done in a few different ways, but
all are awkward and/or inefficient :
a = dict(a=1,c=3)
b = dict(a=0,b=2)
Method 1:
for k in b:
if k not in a:
a[k] = b[k]
Method 2:
temp = dict(b)
temp.update(a)
a = temp
This patch adds a merge() method to the dict object,
with the same signature and usage as the update()
method. Under the hood, it simply uses PyDict_Merge()
with the override parameter set to 0 instead of 1.
There's nothing new, therefore : the C API already
provides this functionality (though it is not used in
the dictobject.c scope), so why not expose it ? The
result is :
a = dict(a=1,c=3)
b = dict(a=0,b=2)
a.merge(b)
assert a == dict(a=1,b=2,c=3)
----------------------------------------------------------------------
>Comment By: Guido van Rossum (gvanrossum)
Date: 2006-01-01 12:55
Message:
Logged In: YES
user_id=6380
I don't think we need to provide every possible permutation
of existing operations.
----------------------------------------------------------------------
Comment By: Raymond Hettinger (rhettinger)
Date: 2006-01-01 01:17
Message:
Logged In: YES
user_id=80475
The example is only slightly complicated by the implicit
requirement to keep b unchanged; otherwise, it is easy
enough to swap the dicts before updating: a,b=b,a;
a.update(b).
Anyway, I do not think the use case is sufficiently common
or cumbersome to warrant making the mapping API more complex.
Guido?
----------------------------------------------------------------------
You can respond by visiting:
https://sourceforge.net/tracker/?func=detail&atid=305470&aid=1391204&group_id=5470
_______________________________________________
Patches mailing list
[email protected]
http://mail.python.org/mailman/listinfo/patches