Dictionaries

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Wed Oct 18 12:07:08 EDT 2006


On Wed, 18 Oct 2006 08:24:27 -0700, Lad wrote:

> How can I add two dictionaries into one?
> E.g.
> a={'a:1}
> b={'b':2}
> 
> I need
> 
> the result {'a':1,'b':2}.
> 
> Is it possible?

What should the result be if both dictionaries have the same key?

a={'a':1, 'b'=2}
b={'b':3}

should the result be:
{'a':1, 'b'=2}  # keep the existing value
{'a':1, 'b'=3}  # replace the existing value
{'a':1, 'b'=[2, 3]}  # keep both values
or something else?

Other people have already suggested using the update() method. If you want
more control, you can do something like this:

def add_dict(A, B):
    """Add dictionaries A and B and return a new dictionary."""
    C = A.copy()  # start with a copy of A
    for key, value in B.items():
        if C.has_key(key):
            raise ValueError("duplicate key '%s' detected!" % key)
        C[key] = value
    return C


-- 
Steven.




More information about the Python-list mailing list