Tuesday, 25 November 2008

Dictionary in love

Merging two dictionaries. It should be easy and it is. Just use the update() method of one of the dictionaries:

d1 = { 'a': 1, 'b': 2}
d2 = {'b': 2, 'c': 3}
d1.update(d2)

d1 is now {'a': 1, 'c': 3, 'b': 2}

But often I don't want to transform one of dictionaries, I want to create a third from the combination of the two. I could make a deep copy of one of the dictionaries and update that (badness), or go through the items and merge (more badness).

And here is where dict() comes to the rescue once again:

d3 = dict(d1, **d2)

That's it; merged -- and it's pretty damn fast too.

No comments: