I have a data structure that looks like this:

a = {
     'red': ['yellow', 'green', 'purple'],
     'orange': ['fuschia']

This is the code I write to add new elements:

if a.has_key(color):
    a[color] = [path]

Is there a shorter way to write this?


1 Answer 1


You can use collections.defaultdict:

from collections import defaultdict

mydict = defaultdict(list)

Now you just need:


defaultdict is a subclass of dict that can be initialized to a list, integer...

btw, the use of has_key is discouraged, and in fact has_key has been removed from python 3.2.
When needed, use this by far more pythonic idiom instead:

if color in a:
  • \$\begingroup\$ even better is try: a[color].append(path) except KeyError: a[color] = [path] ... and this comment formatting is broken :) \$\endgroup\$
    – blaze
    Dec 21, 2011 at 8:58
  • 1
    \$\begingroup\$ @blaze try/except is better? I'd say not. \$\endgroup\$ Dec 24, 2011 at 21:24
  • \$\begingroup\$ if try is usually successful and exception isn't raised - it's effective. one less "if" to check. \$\endgroup\$
    – blaze
    Dec 26, 2011 at 13:11
  • \$\begingroup\$ lots of stuff happening around checking whether operation goes right and whether exception is thrown. besides the semantics of "exception" should be that something, well, exceptional is taking place. I'd avoid using exceptions for regular code flow if a convenient alternative exists \$\endgroup\$
    – Nicolas78
    Dec 26, 2011 at 15:39

Not the answer you're looking for? Browse other questions tagged or ask your own question.