Dictionaries

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Wed Oct 18 13:00:40 EDT 2006


On Wed, 18 Oct 2006 09:31:50 -0700, Lad wrote:

> 
> Steven,
> Thank you for your reply and question.
> 
>>
>> What should the result be if both dictionaries have the same key?
> The answer: the values should be added together and assigned to the key
> That is
> {'a':1, 'b':5}
> ( from your example below)
> 
> Is there a solution?

Of course there is a solution. You just have to program it.

Look again at my example code before:

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


Can you see how to modify this function to do what you want?

(Hint: instead of raising a ValueError exception, you want to do something
else.)


-- 
Steven.




More information about the Python-list mailing list