how to join two Dictionary together?

Iain King iainking at gmail.com
Tue Aug 30 16:56:39 CEST 2005


Iain King wrote:
> DENG wrote:
> > dict1={...something...}
> >
> > dict2={...somethind else ..}
> >
> > dict1 + dict2
> >
> >
> > that's does works ..:(, it's not like List...
> >
> >
> > anyone can tell me how to get it?
> >
>
> Uh, I'm just learning python too, so there may be a much simpler way to
> do this, but you could:
>
> dict3 = {}
> for k,i in dict1.iteritems():
>     dict3[k] = i
> for k,i in dict2.iteritems():
>     dict3[k] = i
>
> Think this should work.  Obviously, if the same key appears in both
> dict1 and dict2 then dict2's value will overwrite dict1's.
>
> Iain

Or, on reading the tutorial a bit more thoroughly, you can do:

dict1.update(dict2)

which will add all of dict2's key:value pairs to dict1

Iain




More information about the Python-list mailing list