Dictionaries

Lad python at hope.cz
Thu Oct 19 09:22:10 CEST 2006


Steven,
Thank you for help;
Here is a code that works in a way I need


A={'c':1,'d':2,'e':3,'f':2}
B={'c':2,'e':1}
if len(A)>=len(B):
	Delsi=B
	C = A.copy()
else:
	Delsi=A
	C = B.copy()

for key, value in Delsi.items():
	if C.has_key(key):
		C[key]=C[key]+value
	else:
		C[key]=value



How easy :-)
Regards,
L.

Steven D'Aprano wrote:
> 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