Dictionaries
Lad
python at hope.cz
Wed Oct 18 12:31:50 EDT 2006
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?
Thanks for the reply
L.
>
> 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