# Shorter way to write list-as-dict-value in Python?

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].append(path)
else:
a[color] = [path]


Is there a shorter way to write this?

## locked by Jamal♦Jul 27 '15 at 22:01

This question exists because it has historical significance, but it is not considered a good, on-topic question for this site so please do not use it as evidence that you can ask similar questions here. This question and its answers are frozen and cannot be changed. See the help center for guidance on writing a good question.

You can use collections.defaultdict:

from collections import defaultdict

mydict = defaultdict(list)


Now you just need:

mydict[color].append(path)


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

• even better is try: a[color].append(path) except KeyError: a[color] = [path] ... and this comment formatting is broken :) – blaze Dec 21 '11 at 8:58
• @blaze try/except is better? I'd say not. – Paul Hankin Dec 24 '11 at 21:24
• if try is usually successful and exception isn't raised - it's effective. one less "if" to check. – blaze Dec 26 '11 at 13:11
• 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 – Nicolas78 Dec 26 '11 at 15:39