Showing posts with label dict. Show all posts
Showing posts with label dict. Show all posts

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.

Writing a dictionary like Dr. Johnson

Typically when I used create a dictionary of elements, I employed the tried and true method declaration followed by element addition:

d = {}
d['a'] = 1
d['b'] = 2
...

Now I find I favour a slightly more compact and pythonic means, using the built-in dict() function:

d = dict( a = 1, b = 2, ... )

Both render the same dictionary:

{'a': 1, 'b': 2 ... }