Tuesday, 25 November 2008

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 ... }

No comments: