[Tutor] Merging dictionaries

Norman Khine norman at khine.net
Thu Aug 7 14:16:49 CEST 2008


Thank you all for the replies.
Norman

On 8/7/08, wesley chun <wescpy at gmail.com> wrote:
> hmmm, somewhat off-topic, i was partially confused by the Subject
> line.  i thought this post was about merging *dictionaries* and not
> merging the *contents of multiple dictionaries' values*.
>
> for those who are interested in the former, you use the update()
> method and here is an example:
>
> >>> d1 = dict(zip(range(3), range(3)))
> >>> d1
> {0: 0, 1: 1, 2: 2}
> >>> d2 = dict(zip(range(2,5), [i*2 for i in range(2, 5)]))
> >>> d2
> {2: 4, 3: 6, 4: 8}
> >>> d1.update(d2)
> >>> d1
> {0: 0, 1: 1, 2: 4, 3: 6, 4: 8}
>
> notice that the update will replace any existing key with the
> corresponding value of the argument dict.
>
> cheers,
> -- wesley
> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
> "Core Python Programming", Prentice Hall, (c)2007,2001
>  http://corepython.com
>
> wesley.j.chun :: wescpy-at-gmail.com
> python training and technical consulting
> cyberweb.consulting : silicon valley, ca
> http://cyberwebconsulting.com
>


More information about the Tutor mailing list