photo
Jordan Sissel
geek

Fri, 14 Jul 2006

Python's dict objects can be merged

Much to my surprise, python dict objects can be merged. I've needed this a few times but never knew about it mostly due to 'pydoc dict' not mentioning 'merge' anywhere.
>>> a = { 1: 2, 3: 4 }
>>> b = { 1: 100, 5: 6 }
>>> b.update(a)
>>> print b
{1: 2, 3: 4, 5: 6}
dict.update() takes any number of arguments, all of which must be dict objects. This lets you merge serveral dicts into one. Conflict resolution, it seems, is "last one in wins."

Comments: 3 (view comments)
Tags:
Permalink: /geekery/python-dict-merging
posted at: 03:42


3 responses to 'Python's dict objects can be merged'

niffshack posted at Sat Aug 5 14:32:32 2006...
Thanks, man! Just what I needed.

Came across your blog via google, in search of just this.

It is in the documentation, but I never would have thought to look for a method named "update"...

Jim Ostrowski posted at Thu Mar 1 19:46:05 2007...
Thanks for that tidbit!! It was exactly what I needed, and the docs weren't getting me there...

na posted at Wed Jul 2 05:46:15 2008...
Consider this helper function. It does not mutate the original and works with any number of arguments.

import operator

def DictMerge(*dicts):
  return dict(reduce(operator.add, [x.items() for x in dicts]))


Leave a reply

You need javascript enabled to use this form. Anti-spam efforts ongoing. Also, if the comment doesn't show up, it's because the form expired. Go back and copy your comment, reload the form, and resubmit. Apologies if this is a hassle, I'm just playing with antispam methods right now. If this insists on not working, please email me about it.

Name (required)
E-mail (optional, if you want me to be able to email you back)
URL (also optional)
Comment:


Search this site

Navigation

Metadata

Home About Resume My Code (SVN)

Articles

ARP Security Dynamic DNS with DHCP OpenLDAP+Kerberos+SASL PPP over SSH SSH Security: /bin/false Week of Unix Tools Work Efficiency

Projects

fex firefox tabsearch firefox urledit grok keynav liboverride newpsm (FreeBSD) nis2ldap pam_captcha poor man's backup Solaris audio utility xboxproxy xdotool xmlpresenter xpathtool misc scripts

Presentations

Yahoo! Hack Day '06 Unix Essentials Vi/Vim Essentials

Tag Cloud

Calendar

< July 2006 >
SuMoTuWeThFrSa
       1
2 3 4 5 6 7 8
9101112131415
16171819202122
23242526272829
3031     

Friends

BarCamp Kent Brewster Tantek Çelik John Resig Wesley Shields Tyler Shields

Technorati